I am newbie on MongoDb. What is the use of db.connect('once', function(){});
This will create the connection once per request??
This will by default close the connection when this job is done??
mongoose.connect(uri, options);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(err, resp){
console.log(resp);
});
Any help is Appreciated.
I am newbie on MongoDb. What is the use of db.connect('once', function(){});
This will create the connection once per request??
This will by default close the connection when this job is done??
mongoose.connect(uri, options);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(err, resp){
console.log(resp);
});
Any help is Appreciated.
Share Improve this question asked Apr 2, 2018 at 8:28 AnkitAnkit 1,0111 gold badge12 silver badges30 bronze badges 1- mongoosejs.com/docs – TGrif Commented Apr 2, 2018 at 9:25
3 Answers
Reset to default 9when you use 'once' it signifies that the event will be called only once i.e the first time the event occurred like here in this case the first time when the connection is opened ,it will not occur once per request but rather once when the mongoose connection is made with the db
while the 'on' signifies the event will be called every time that it occurred
It is the callback to be executed when the given event is generated. In your example to the function will be called when the connection to mongodb is open i.e. the connection is successful.
Here db.on
it is kind of error handling you can use then
and catch
, And also db.once
means the exactly like once that is to say once the connection is okay then do this for example console.log
.