2012-02-16 119 views
10

我試圖通過Node.js與MongoDB進行接口,並且在count()方法中遇到了一些麻煩。我正在使用node-mongodb-native,它看起來像我在做什麼應該工作。我的代碼示例:MongoDB計數集合Node.js

var get_total_num_docs = function(db_client, query, cb){ 
    db_client.collection(query['collection'], function(e, coll) { 
    coll.find(query.params, query.options, function (e, cursor) { 
     cursor.count(function (e, count) { 
     console.log(count); 
     return cb(e, count); 
     }); 
    }); 
    }); 
}; 

我相信,一切存在(又名都定義科爾和光標),但它只是如果我的query.params字段爲空的作品(即發現整個集合的計數)。所以如果我試圖用任何種類的選擇器來運行查找,查找就可以工作,但是它拒絕指望返回的光標。從我在網上閱讀的內容看,這看起來是正確的方式,但顯然有些問題。感謝您的幫助!

+0

你是什麼意思時,你說拒不算?它給你錯誤的計數或拋出錯誤? – 2012-02-16 20:24:15

+0

就像在它從字面上只是永遠不會完成,也就是從來沒有調用傳遞給計數的回調。我已經運行了大約10分鐘,它只是從來沒有完成。 coll.find調用需要非常短的時間,但是某些東西並不適用於計數。 – MrJaeger 2012-02-16 20:26:20

+0

你有沒有試過''console.log''ging你收到的每個錯誤對象? 什麼是正在使用的查詢參數和選項? – 2012-02-16 22:05:57

回答

18

如果你不需要光標,你應該寫你這樣的代碼:

var get_total_num_docs = function(db_client, query, cb){ 
    db_client.collection(query['collection'], function(e, coll) { 
    coll.find(query.params, query.options).count(function (e, count) { 
     console.log(count); 
     return cb(e, count); 
    }); 
    }); 
};