最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose.connection('once') what does it mean - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 9

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

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.

发布评论

评论列表(0)

  1. 暂无评论