Javascript 与nodejs的MongoDB连接返回承诺<;待定>;
大家早上好! 几周前,我开始学习javascript、node.js和mongo,所以我还是个新手。今天我想做一个简单的任务。我想向mongoDB添加一个简单的文档,并检查一个条件。 所以我想说:Javascript 与nodejs的MongoDB连接返回承诺<;待定>;,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,大家早上好! 几周前,我开始学习javascript、node.js和mongo,所以我还是个新手。今天我想做一个简单的任务。我想向mongoDB添加一个简单的文档,并检查一个条件。 所以我想说: 连接到mongoDB 在插入文档之前,我想检查是否已有一个现有名称。如果已获取名称,则返回一个错误 插入文档 我这样做: function addDocument(req, res){ //did some statements to check valid document f
function addDocument(req, res){
//did some statements to check valid document fields and values
MongoClient.connect(uri, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
console.log('Connected to Database')
let db = client.db('data');
let serviceCollection = db.collection('services');
let checkName = serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
return result;
})
console.log(checkName);//this doesn't print anything and returns the pending promise
//here I want to put a conditional statement like: if(checkName>0) return res.send("name already exists")
serviceCollection.insertOne(service)
})
return res.send("Done!")
}
如果我删除console.log或“If”语句,它就会工作。它将文档添加到数据库中,但具有重复的“名称”。
如果我使用以下命令修改console.log:
checkName.then(r=>{console.log(r)})
然后它打印具有给定名称的文档数。我应该怎么做才能用“if”语句处理这个问题,并在大于0时返回错误
JSON文档如下所示:
{
"name": "marco",
"field2": "example"
//etc
}
此函数导出到app.js,并在post方法中用作回调。
多谢各位 您的问题是您没有等待承诺兑现。您可以将代码移动到承诺兑现后,或者等待承诺兑现。看一看。将代码从
let checkName = serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
return result;
})
到
或者等待承诺兑现后再使用其回报值。i、 e
serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
console.log(result);//this doesn't print anything and returns the pending promise
//here I want to put a conditional statement like: if(checkName>0) return res.send("name already exists")
serviceCollection.insertOne(service)
})
})
谢谢,但如果我放置wait,它会抛出一个错误,上面写着“wait只能在异步函数中使用”。我把这个关键字放在
函数addDocument(res-req)
之前,但它仍然给我同样的错误。
serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
console.log(result);//this doesn't print anything and returns the pending promise
//here I want to put a conditional statement like: if(checkName>0) return res.send("name already exists")
serviceCollection.insertOne(service)
})
})