1

Could you please assist me with seeding the database in nextjs?

This is the main code of seeder.js

import Product from '/models/productModel';
import products from '/data/products';
import dbConnect from '/config/dbConnect';

dbConnect();

const seedProducts = async () => {
  try {
    await Product.deleteMany();
    console.log('Products are deleted');

    await Product.insertMany(products);
    console.log('All Products are added.');

    process.exit();
  } catch (error) {
    console.log(error.message);
    process.exit();
  }
};

seedProducts();

and this is the scripts in package

package.json

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "seeder": "node utils/seeder"
  },

when I run node seeder, I get the below error message

(node:27824) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\tarek\Desktop\Code\utils\seeder.js:1
import Product from '/models/productModel';
^^^^^^

SyntaxError: Cannot use import statement outside a module

So, I renamed the file extension into mjs then, the following error message

node:internal/modules/cjs/loader:959
  throw err;
  ^

Error: Cannot find module 'C:\Users\tarek\Desktop\Code\utils\seeder'
    at Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
    at Module._load (node:internal/modules/cjs/loader:804:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

added the extension to the filename at package json script

"seeder": "node utils/seeder.mjs"

Still got error message:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\models\productModel' imported from C:\Users\tarek\Desktop\Code\utils\seeder.mjs at new NodeError (node:internal/errors:387:5) at finalizeResolution (node:internal/modules/esm/resolve:404:11) at moduleResolve (node:internal/modules/esm/resolve:965:10) at defaultResolve (node:internal/modules/esm/resolve:1173:11) at nextResolve (node:internal/modules/esm/loader:173:28) at ESMLoader.resolve (node:internal/modules/esm/loader:852:30) at ESMLoader.getModuleJob (node:internal/modules/esm/loader:439:18) at ModuleWrap. (node:internal/modules/esm/module_job:76:40) at link (node:internal/modules/esm/module_job:75:36) { code: 'ERR_MODULE_NOT_FOUND' }

1 Answer 1

0
npx tsx your-script.mjs

I hope this solves your problem. Don't ask me why.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.