gpt4 book ai didi

javascript - 使用 MongoDB 和 Nodejs 计算未定义的数量

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:38 26 4
gpt4 key购买 nike

问题

Node.js MongoDB 库始终返回未定义的 collection.count({})。这个问题已经被发布和回答了很多次,我确信已经完成了所有以前的解决方案,但似乎没有一个有效,而且我总是未定义。

作为问题的背景,我正在制作一个作业自动化器,在添加新作业之前,我想确保数据库中已存在 0 条记录,它们与要添加的新作业同名(即名称是唯一的)。 编辑:在某些情况下,我确实希望允许重复项,因此我不想使用索引并在数据库级别禁止重复项。

代码

在这种情况下,count 内的 console.log() 仅打印 undefined。在本例中,我在调试过程中放入了一个空查询字符串(当前未测试名称冲突)。

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 Problems Part//End of Problems 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() 中的错误,所以我在 count() block 中添加了 if(err)console.log(err); ,结果错误是:

{ [MongoError: server localhost:27017 sockets closed] 
name: 'MongoError',
message: 'server localhost 27017 sockets closed' }

我不太明白,因为在代码的其他部分,我可以使用相同的 connect() 和 collection() 调用并将插入到数据库中。基于此有什么见解吗?

任何帮助将不胜感激!

最佳答案

让我们处理一下问题的意图:

I am making a Job Automator, and before adding a new job, I want to make sure that 0 records already exist in the database that have the same name as the new job being added (i.e. names are unique).

无需通过 javascript 进行劳动,只需 set a unique index在名称键上。在蒙戈中:

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

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

关于javascript - 使用 MongoDB 和 Nodejs 计算未定义的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com