【问题标题】:How to get a callback on MongoDB collection.find()如何在 MongoDB collection.find() 上获取回调
【发布时间】:2012-07-24 13:58:07
【问题描述】:

当我在 MongoDB/Node/Express 中运行 collection.find() 时,我想在它完成时得到一个回调。正确的语法是什么?

 function (id,callback) {

    var o_id = new BSON.ObjectID(id);

    db.open(function(err,db){
      db.collection('users',function(err,collection){
        collection.find({'_id':o_id},function(err,results){  //What's the correct callback synatax here?
          db.close();
          callback(results);
        }) //find
      }) //collection
    }); //open
  }

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    这是正确的回调语法,但find 提供给回调的是Cursor,而不是文档数组。因此,如果您希望您的回调以文档数组的形式提供结果,请在光标上调用 toArray 以返回它们:

    collection.find({'_id':o_id}, function(err, cursor){
        cursor.toArray(callback);
        db.close();
    });
    

    请注意,您的函数回调仍然需要提供err 参数,以便调用者知道查询是否有效。

    2.x 驱动程序更新

    find 现在返回光标而不是通过回调提供光标,因此典型用法可以简化为:

    collection.find({'_id': o_id}).toArray(function(err, results) {...});
    

    或者在这种需要单个文档的情况下,使用findOne 会更简单:

    collection.findOne({'_id': o_id}, function(err, result) {...});
    

    【讨论】:

    【解决方案2】:

    根据 JohnnyHK 的回答,我只是将我的调用封装在 db.open() 方法中并且它起作用了。谢谢@JohnnyHK。

    app.get('/answers', function (req, res){
         db.open(function(err,db){ // <------everything wrapped inside this function
             db.collection('answer', function(err, collection) {
                 collection.find().toArray(function(err, items) {
                     console.log(items);
                     res.send(items);
                 });
             });
         });
    });
    

    希望它作为示例有所帮助。

    【讨论】:

    • 他们称之为...回调地狱!它开始......
    • 我正在使用相同的但我得到 db.open is not function 错误你能帮我吗
    猜你喜欢
    • 1970-01-01
    • 2012-12-21
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多