I have been following online instructions to set up a mongodb database using mongoose on node.js. I have managed to get the mongodb running and listening on port 27017, however when I run my connection code in node.js I get a successful response even when the mongo.db isn't running and I don't see any updates on the mongo.db to say it has received any data.
I have tried quite a few different examples from the internet but can't get any of them to work.
So I have my MongoDB
saying:
2019-03-26T12:00:46.039+0000 I NETWORK [initandlisten] waiting for connections on port 27017
This is the basic code I am trying to get to work as my original API wasn't working:
//sample.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', function(err){
if(!err) console.log('Successfully Connected');
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
});
I receive this response when I run
node sample.js
Successfully Connected
localhost
27017
But I receive this response even when my mongo.db has been shut down, so I think there is some error, I'm not sure how to check if they are connecting properly.
this works for me. try to set some debugging to find out what is happening.
mongoose.set('debug', true);
mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true})
.then(() => {
console.log('connected to the db');
})
.catch(err => {
console.log('connection failed ' + err);
});
I think you have to check the API to connect.
https://mongoosejs.com/docs/connections.html
Second parameter is option and third is callback - but u seem to have passed callback as second param - also, check what are you getting as response
mongoose.connect(uri, options, function(error) { // Check error in initial connection. There is no 2nd param to the callback. }); // Or using promises mongoose.connect(uri, options).then( () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ }, err => { /** handle initial connection error */ } );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.