I have this mongoose.connect statement in my server.js file:
const db = mongoose.connect(config.db, {
'useNewUrlParser': true,
'useUnifiedTopology': true,
'useFindAndModify': false,
'useCreateIndex': true
}, function(err, database) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}else{
console.log("db connected");
}
});
// Init the express application
const app = require('./config/express')(db);
But when I reference the db
constant in my express file, it keeps coming up as undefined
.
What am I doing wrong here?
CodePudding user response:
You should not pass it any callback. In that case mongoose would return you a Promise, which you'd need to await
or .then()
. E.g.
mongoose.connect(config.db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}).then((db) => {
// Init the express application
const app = require('./config/express')(db);
});