2013-03-25 32 views
2

我:找到的每個文件執行回調時,貓鼬執行find()方法

​​

如果函數返回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的使用:http://mongodb.github.com/node-mongodb-native/api-generated/cursor.html#each


編輯:也許這是可以做到聽從流數據的事件,推動該文件到一個數組:

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

回答

3

正如我說,流:

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)); 
    }); 
}); 
+0

這是你所需要的? – shelman 2013-03-25 15:34:51

+0

是的,但我注意到這比使用mongodb中的每個()慢得多 – 2013-03-25 15:41:53

+1

在這種情況下,您可以從Mongoose中下載到本地驅動程序中,如[this]中所述(http:// stackoverflow.com/questions/10519432/how-to-do-raw-mongodb-operations-in-mongoose)問題。 – shelman 2013-03-25 15:46:58

1

好像你也許能夠使用query stream做你想要的東西 -^h無論如何,即使有一個調用,你仍然基本上遍歷所有返回的文檔,只需要一點點語法糖。

0

爲貓鼬/ eachAsync簡單示例代碼,可以是有用的對於這種情況:

functionProcess = (callback) => { 

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

}