2016-12-01 61 views
0

我該如何打印集合中的所有項目。我正在使用此代碼,並且可以在集合中少於100個項目的情況下正常工作。如何從承諾中打印100多份來自mongoDB集合的文檔

當我有更多的只是印刷:

ITEMS: undefined 
1 
ITEMS: undefined 
2 
..... 
ITEMS: undefined 
99 
ITEMS: undefined 
100 
ITEMS: undefined 

C:\Users\rmuntean\Documents\Automatizare\NodeJS\node_modules\mongodb\lib\utils.js:98 process.nextTick(function() { throw err; });

TypeError: callback is not a function

我也試過指定者,是同樣的問題。

沒有承諾的代碼工作正常,我可以打印所有項目。

var bluebird = require('bluebird'); 
var MongoClient = require('mongodb').MongoClient; 
var MongoCollection = require('mongodb').Collection; 

bluebird.promisifyAll(require('mongodb')); 

const connection = "mongodb://localhost:27017/test"; 

var cc = 0; 
var theDb 
var theCollection 

MongoClient.connectAsync(connection) 
    .then(function(db) { 
    theDb = db; 
    return theDb.collectionAsync("test_array"); 
    }) 
    .then(function(collection) { 
    theCollection = collection; 
    return theCollection.findAsync({}); 
    }) 
    .then(function(cursor) { 
    cursor.forEach((err, items) => { 
     console.log("ITEMS:", items); 
     cc++ 
     console.log(cc); 
    }); 
    }) 
    .finally(() => { 
    theDb.close() 
    }) 
    .catch((err) => { 
    console.log(err); 
    err(500); 
    }); 

我使用:

"mongodb": "^2.2.12", 
"bluebird": "^3.4.6", 

我在做什麼錯?

+0

'cursor.forEach((ERR,項目)'你不在這裏返回任何東西,所以你最終獲取調用立竿見影。你可以包裝在foreach一個無極裏面,我beleive當所有項目完成項目' '(將會是錯誤的。) – Keith

回答

0

由於您的forEach沒有返回承諾,finally會立即被調用,IOW:theDb.close()在您甚至有機會迭代結果之前就會被調用。這解釋了undefined

所以你需要控制何時完成forEach,我沒有使用monogoDb,但看着文檔,如果文檔是空的,這意味着列表結束。

有了承諾,總是從內另一then方法要記住,如果你不回一個承諾,在未來then/finally等將被調用,而不必等待,你基本上已經打破了諾言鏈。

所以希望以下內容會有所幫助。

.then(function(cursor) { 
    return new Promise((resolve, reject) => { 
    cursor.forEach((err, items) => { 
     if (err) return reject(err); 
     if (!items) return resolve(); //no more items 
     console.log("ITEMS:", items); 
     cc++ 
     console.log(cc); 
    }); 
    }); 
}) 
+0

謝謝,我使用了你的建議和代碼,並且正在工作: 然後(函數(cursor){ }返回新的Promise((resolve,reject)=> {cursor} {(err, (); console.log(「ITEMS:」,items); cC++ console.log(cc); });();} 如果(cursor.isClosed())return resolve}); }) – mnbv