I am currently working on an assignment that involves a traveler website and creating a database that stores things like code, name, and length. I am trying to seed data into a database, but I am getting an error that says:
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');
I thought I installed seedgoose using my terminal. What could be the problem? Here is part of my code:
db.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);
seed.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 };
}
Moving the module.exports = { seed }; outside of the function scope helped and adding another underscore to _dirname helped.
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 };