如何在 MongoDB collection.find() 上获得回调 [英] How to get a callback on MongoDB collection.find()

查看:35
本文介绍了如何在 MongoDB collection.find() 上获得回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. What's the correct syntax for this?

 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
  }

推荐答案

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

That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:

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

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

Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.

2.x 驱动程序更新

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

find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:

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

或者在需要单个文档的情况下,使用 findOne:

Or in this case where a single document is expected, it's simpler to use findOne:

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

这篇关于如何在 MongoDB collection.find() 上获得回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆