你能帮我在nextjs中播种数据库吗?
这是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();
这是脚本包
package.json
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"seeder": "node utils/seeder"
},
当我运行node seeder时,我得到以下错误消息
(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
所以,我将文件扩展名重命名为mjs然后,下面的错误消息
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: []
}
在json脚本包中添加了文件名的扩展名
"seeder": "node utils/seeder.mjs"
仍然收到错误消息:
错误[ERR_MODULE_NOT_FOUND]:找不到模块'C:从C导入的\models\productModel':\Users\tarek\Desktop\Code\utils\seeder。mjs at new NodeError(node:内部/错误:三百八十七:5)at finalizeResolution(node:internal/modules/esm/resolve:404:11)at moduleResolve(node:internal/modules/esm/resolve:九六五:10)at defaultResolve(node:internal/modules/esm/resolve:1173:11)在nextResolve(节点:internal/modules/esm/loader:一百七十三:28)在ESMLoader。resolve(node:internal/modules/esm/loader:八五二:30)在ESMLoader。getModuleJob(节点:internal/modules/esm/loader:四百三十九:18)在ModuleWrap。(node:internal/modules/esm/module_job:76:40)at link(node:internal/modules/esm/module_job:75:36){ code:'错误_未找到' }
1条答案
按热度按时间lymnna711#
我希望这能解决你的问题。别问我为什么