[英]Count Undefined with MongoDB and Nodejs
問題
Node.js MongoDB庫始終為collection.count({})
返回undefined。 這個問題已經發布並回答了無數次,並且我已經確定會經歷所有以前的解決方案,但是似乎沒有一個可行,而且我總是不確定。
作為問題的背景,我正在創建一個Job Automator,然后在添加新作業之前,我要確保數據庫中已經存在0條記錄,這些記錄與要添加的新作業具有相同的名稱(即名稱是唯一的) )。 編輯 :在某些情況下,我確實希望允許重復,所以我不想在數據庫級別使用索引和禁止重復。
碼
在這種情況下,內部count
的console.log()
僅打印未定義。 在這種情況下,我將一個空的查詢字符串作為調試的一部分(當前未測試名稱沖突)。
add: function(io, newJob)
{
//mc is where require('mongodb').MongoClient is saved
//connectionString contains a valid connection string
//activeCollection contains the name of the collection
//(I am sure mc, connectionString and activeCollection are valid)
//I know this as I have used them to insert documents in previous parts
mc.connect(connectionString, function(err,db)
{
if(err)
throw err;
else
{
db.collection(activeCollection, function(err,collection)
{
if(err)
throw err;
//Start of problematic part
//See also "What I've tried" section
collection.count({},function(err,count)
{
console.log(count);
});
//End of problematic part
//Omitting logic where I insert records for brevity,
//as I have confirmed that works previously.
});
}
db.close();
});
}
我嘗試過的
我已經閱讀了前面的問題,並用以下代碼塊將之前代碼塊中//End of problematic part
//Start of problematic part
與//End of problematic part
之間的內容替換為:
完全中斷回調(也顯示未定義):
function countDocs(callback)
{
collection.count({},function(err, count)
{
if(err)
throw err;
callback(null, count);
}
}
countDocs(function(err,count)
{
if(err)
throw err;
console.log(count);
});
我什至嘗試過我不知道會做的事情
var count = collection.count({});
新(1/28/16)
我有點草率地不檢查我的count()
的錯誤,所以我添加了if(err)console.log(err);
進入count()
塊,結果錯誤是:
{ [MongoError: server localhost:27017 sockets closed]
name: 'MongoError',
message: 'server localhost 27017 sockets closed' }
我不太了解,因為在代碼的其他部分,我可以使用相同的connect()和collection()調用,並使插入到數據庫中就很好了。 任何基於此的見解?
任何幫助將非常感激!
讓我們處理這個問題的意圖:
我正在創建一個Job Automator,在添加新作業之前,我要確保數據庫中已經存在0條記錄,這些記錄與要添加的新作業具有相同的名稱(即名稱是唯一的)。
無需通過javascript進行操作,只需在名稱鍵上設置唯一索引即可 。 在mongo中:
db.collection.ensureIndex( { name: 1 }, { unique: true } )
然后,當您插入文檔時,使用try / catch塊捕獲創建具有重復名稱的文檔的任何嘗試。
您可以使用collection.find().toArray(function(err,documents) { ...});
,如果沒有文檔與您的查詢匹配,則返回一個空數組。 檢查數組的length
屬性應該等效於您嘗試使用count()
實現的功能。
文檔中的更多信息: https : //mongodb.github.io/node-mongodb-native/api-genic/cursor.html#toArray
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.