'Mongoose.connection('once') what does it mean
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.
Solution 1:[1]
when 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
Solution 2:[2]
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.
Solution 3:[3]
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 conecction is ok then do this for example cosole.log.
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 | Kirti Chaturvedi |
| Solution 2 | Mohit Mutha |
| Solution 3 | Mohammad Bagher Bayaty |
