node.js – Await SyntaxError in nodeJS: await is only valid in async functions and the top level bodies of modules

It may sound silly, but I can’t find why I am getting this error:-

C:\node-project\api.testsite\seed\index.js:20
await User.create(user);
^^^^^

SyntaxError: await is only valid in async functions and the top level
bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object. (C:\node-project\api.testsite\database\connection.js:2:21)
at Module._compile (node:internal/modules/cjs/loader:1103:14)

This is my code. It’s pretty simple.

const moment     = require("moment");
const bc         = require("bcryptjs");

var userList     = require("./users");
var User         = require("../app/Models/User");

module.exports = {
  seedUser: async function (db) {
    const Users = db.collection("users");
    const userCount = await User.count();
    if (userCount === 0) {
      userList.map((user) => {
        console.log(user, 'hioo')
        const DtCr = new Date();
        user.created_date = DtCr;
        user.modified_date = DtCr;
        user.created_at = moment().valueOf();
        user.updated_at = moment().valueOf();
        console.log(user)
        await User.create(user);
      });
    }
  }
};

As you see, the function seedUser is itself an async function. Moreover, the loc:-

const userCount = await User.count();

isn’t causing any error. Then why the line:-

await User.create(user);

is causing error? If the error is due to await inside function seedUser, then shouldn’t both have the same issue?

Read more here: Source link