'Mongoose.connect keeps coming back undefined
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?
Solution 1:[1]
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vasyl Boroviak |
