计数未定义与MongoDB和Nodejs

问题

Node.js MongoDB库始终返回未定义的collection.count({}) 。 这个问题已经发布和回答了很多次,我一直坚信所有以前的解决scheme,但是没有一个能够工作,而且我总是不确定。

作为问题的背景,我正在创build一个Job Automator,并且在添加一个新的作业之前,我想确保数据库中已经存在的0个logging与正在添加的新作业名称相同(即名称是唯一的)。 编辑 :有几个我想要允许重复的情况下,所以我不想在数据库级别使用索引和dis-allow重复。

在这种情况下, console.log()内部count只是打印未定义。 在这种情况下,我将一个空的查询string作为debugging的一部分(目前不testing名称冲突)。

 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(); }); } 

我试过了

我已经阅读了前面的问题,并将//Start of problematic part和/或前面的代码块//End of problematic partreplace为以下块之间的内容:

完全打破callback(也打印未定义):

 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()调用,并插入数据库就好了。 基于这个的任何见解?

任何帮助将非常感激!

让我们来处理这个问题的意图:

我正在创build一个Job Automator,并且在添加一个新的作业之前,我想确保数据库中已经存在的与已添加的新作业同名(即名称是唯一的)的logging为0。

而不是通过JavaScript劳动,只需在名称键上设置一个唯一的索引 。 在mongo:

 db.collection.ensureIndex( { name: 1 }, { unique: true } ) 

然后,当您插入文档时,使用try / catch块来捕获任何尝试创build具有重复名称的文档。

你可以使用collection.find().toArray(function(err,documents) { ...}); ,如果没有文档匹配您的查询,则返回一个空数组。 检查数组的length属性应该等同于您用count()实现的内容。

文档中的更多信息: https : //mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toArray