提问人:FireMonkey 提问时间:3/23/2023 最后编辑:FireMonkey 更新时间:3/23/2023 访问量:220
TypeError:种子不是函数
TypeError: seed is not a function
问:
我目前正在完成一项涉及旅行者网站的任务,并创建一个存储代码、名称和长度等内容的数据库。我正在尝试将数据播种到数据库中,但收到一个错误,提示:
TypeError: seed is not a function
at main (C:\Users\marce\src\travlr\app_server\models\db.js:30:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
C:\Users\marce\src\travlr\node_modules\mongoose\lib\connection.js:972
throw new MongooseError('Connection.prototype.close() no longer accepts a callback');
我以为我使用我的终端安装了 seedgoose。可能是什么问题?这是我的部分代码:
数据库 .js
const mongoose = require('mongoose');
const host = process.env.DB_HOST || '127.0.0.1';
const conn_uri = `mongodb://${host}/travlr`;
const {seed} = require('./seed');
// Register models
require('./trips');
mongoose.connection.on('connected', () => console.log('CONNECTED!'));
mongoose.connection.on('error', err => console.log(err));
mongoose.connection.on('disconnected', () => console.log('DISCONNECTED!'));
mongoose.set('strictQuery', false);
// Kill MongoDB connections before exiting app
const gracefulShutdown = (msg, callback) => {
mongoose.connection.close( () => {
console.log(`Mongoose disconnected due to ${msg}`);
callback();
});
}
process.once('SIGUSR2', () =>
gracefulShutdown('nodemon restart', () => process.kill(process.pid, 'SIGUSR2')));
process.on('SIGINT', () =>
gracefulShutdown('app termination', () => process.exit(0)));
async function main() {
await mongoose.connect(conn_uri);
await seed();
}
main().catch(console.log);
种子.js
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
const seed = async function() {
// Seed TRIPS
const trips = JSON.parse(fs.readFileSync(path.join(_dirname, '../../data/trips.json'), 'utf8'));
const trip = mongoose.model('trips');
await trip.deleteMany();
await trip.insertMany(trips);
module.exports = { seed };
}
答:
-1赞
FireMonkey
3/23/2023
#1
移动 module.exports = { seed };在函数范围之外有所帮助,_dirname添加另一个下划线会有所帮助。
const seed = async function() {
// Seed TRIPS
const trips = JSON.parse(fs.readFileSync(path.join(__dirname, '../../data/trips.json'), 'utf8'));
const trip = mongoose.model('trips');
await trip.deleteMany();
await trip.insertMany(trips);
}
module.exports = { seed };
上一个:如何从上下文设定数据库种子
评论
seed
seed.js
seed/index.js
)module.exports = { seed };
应该去函数之后}