I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?
I want to connect my app to a database called 'technicaltest'.
My code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
The console ouput:
> set PORT=3001 && node bin/www
Connected to mongoDB !
Same output for this code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console... But here... The 'connected' event is call anyway.
I think you forgot to add the port(27017) to your mongodb connection. It should be
const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});