TypeError:种子不是函数

TypeError: seed is not a function

提问人:FireMonkey 提问时间:3/23/2023 最后编辑:FireMonkey 更新时间:3/23/2023 访问量:220

问:

我目前正在完成一项涉及旅行者网站的任务,并创建一个存储代码、名称和长度等内容的数据库。我正在尝试将数据播种到数据库中,但收到一个错误,提示:

    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 };
}
JavaScript mongoDB 种子

评论

0赞 Phil 3/23/2023
编辑您的问题以包含您的模块(或seedseed.jsseed/index.js)
0赞 FireMonkey 3/23/2023
我刚刚添加了种子.js @Phil
0赞 qrsngky 3/23/2023
module.exports = { seed };应该去函数之后}
0赞 FireMonkey 3/23/2023
这解决了种子问题。现在我收到一个 ReferenceError,说_dirname未定义
0赞 FireMonkey 3/23/2023
添加另一个下划线修复了 dirname 问题

答:

-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 };