I know the MongoDB database is not connecting because when I enter asdfasdfasdfasdf
I get the "connected to DB" in the console either way.
I have my actual password in the mongodb string instead of <passord>
.
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
app.get('/', (req, res) => {
res.send('We are at home')
})
//Connect to DB
Mongoose.connect(
// 'mongodb srv://myname:<password>@cluster0.9jr1t.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
'asdfasdfasdfasdf',
() => console.log('connected to DB')
)
app.listen(3000);
I hope this is enough information.
CodePudding user response:
You need to connect with the database with proper error handling:
Ex:
mongoose
.connect(connectionString)
.then(() => {
console.log('connected to DB')
});
})
.catch(err => {
console.log(err);
});
app.listen(3000);
To add to this, the ideal way to start the server with app.listen()
is only after a successful DB connection. Otherwise, the server may start without connecting to the DB and would probably lead to complications.
So I suggest this:
mongoose
.connect(connectionString)
.then(() => {
console.log('connected to DB');
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
})
.catch(err => {
console.log(err);
});
CodePudding user response:
url = 'mongodb srv://myname:' password '@cluster0.9jr1t.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, ((err) =>{
if(err){
console.log(err);
}
else{
console.log('db connected');
}
}));
CodePudding user response:
From the Mongoose docs
mongoose.connect(uri, function(error) {
// if error is truthy, the initial connection failed.
})
The callback function is executed whether there is an error or not, the callback should accept a parameter, and test it to see if the connection was successful or not.
Also check out the section on error handling