[英]Node.Js - Return 1 if no matching document is found in MongoDB
Following query is written in MongoDB, I want to modify it such that when there is no matching record it should return 1.以下查询是用 MongoDB 编写的,我想对其进行修改,以便在没有匹配记录时应返回 1。
Code :代码 :
db.collection("uses").find({users:uid}).toArray((err,response) => {
if(err){
throw err;
}
if(response){
res.json(uid);
}
else{
res.json("1");
}
})
.find() would return a cursor & since you're using .toArray()
on a cursor then it would return an array of objects/documents if any matched or else an empty array, So in your below code adding response.length
should work : .find()会返回一个游标 & 因为你在一个游标上使用
.toArray()
那么它会返回一个对象/文档数组(如果有任何匹配)或者一个空数组,所以在你下面的代码中添加response.length
应该工作 :
db.collection("uses").find({users:uid}).toArray((err,response) => {
if(err){
throw err;
}
if(response && response.length){
res.json(uid);
}
else{
res.json("1");
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.