【问题标题】:Execute callback for each document found when mongoose executes find()对 mongoose 执行 find() 时找到的每个文档执行回调
【发布时间】:2013-03-15 02:45:14
【问题描述】:

我有:

Emotion.find (query, "-_id", opts, function (error, e){
    if (error) return cb (error, 500);
    for (var i=0, len=e.length; i<len; i++){
        e[i] = convert (e[i]);
    }
    cb (null, e);
});

如果函数返回 1k 个文档,我必须迭代 1k 次。

如何添加为每个文档执行的回调?比如:

var each = function (e){
    return convert (e);
};

Emotion.find (query, "-_id", opts, each, function (error, e){
    if (error) return cb (error, 500);
    cb (null, e);
});

我基本上需要使用来自 mongodb 的 each():http://mongodb.github.com/node-mongodb-native/api-generated/cursor.html#each


编辑:也许这可以通过从流中侦听数据事件并将文档推送到数组来完成:

http://mongoosejs.com/docs/api.html#query_Query-stream

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    mongoose/eachAsync 的简单示例代码,对这种情况很有用:

    functionProcess = (callback) => {
    
      userModel.find().cursor().eachAsync(user => {
        return user.save().exec();        // Need promise
      }).then(callback);     //Final loop
    
    }
    

    【讨论】:

      【解决方案2】:

      正如我所说,使用流:

      var emotions = [];
      
      Emotion.find (query, "-_id", opts).stream ()
              .on ("error", function (error){
                  cb (error, 500);
              })
              .on ("data", function (doc){
                  emotions.push (convert (doc));
              })
              .on ("close", function (){
                  cb (null, emotions)
              });
      

      编辑:上述解决方案比这慢得多:

      var emotions = [];
      
      //Get the collection... then:
      
      collection.find (query, opts, function (error, cursor){
          if (error) return cb (error, 500);
      
          cursor.each (function (error, doc){
              if (error) return cb (error, 500);
              if (!doc) return cb (null, emotions);
              emotions.push (convert (doc));
          });
      });
      

      【讨论】:

      • 是的,但是我注意到这比使用 mongodb 中的 each() 慢得多
      • 在这种情况下,您可以从 Mongoose 下拉到本机驱动程序,如this 问题中所述。
      • 仅供参考,在本机/更快的情况下,您实际上得到的是 Mongo 对象,而不是 Mongoose 文档(就像使用 lean 进行查询一样)。
      【解决方案3】:

      您似乎可以使用 query stream 来做您想做的事 - 但是,即使使用 each() 之类的调用,您实际上仍然在迭代所有返回的文档,只需一点语法糖。

      【讨论】:

        猜你喜欢
        • 2016-01-08
        • 2018-07-22
        • 2015-12-21
        • 1970-01-01
        • 2018-04-03
        • 2017-04-03
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        相关资源
        最近更新 更多