【发布时间】:2016-03-13 03:52:05
【问题描述】:
我有一个 MongoDB 查询,我在 NodeJS 中运行,如果查询返回 null,则不应该运行 (doc):
collection.find( { name: "HOSTNAME_1" }, {$exists: true}).sort( { _id : -1 } ).limit(1).toArray(function(err, doc){
if (doc) {
res.write("event: add" + '\n');
res.write("data: " + JSON.stringify(doc).substr(1,JSON.stringify(doc).length-2) + "\n\n");
} else if (!doc) {
console.log("No Entry Found!");
}
});
由于某种原因,它仍然运行 doc 函数并在我 curl 时输出它。
event: add
data:
如果我删除 .toArray,我的查询将如下所示:
db.clients.find( { name: "HOSTNAME_1" }, {$exists: true}).sort( { _id : -1 } ).limit(1)
它返回 null 就像它应该的那样,如果我对一个实际存在的项目运行它,它会返回 { "_id" : ObjectId("12345689randomnumber") } 就像它应该的那样。带有.toArray 的东西正在扼杀我的{$exist:true} 错误句柄。
如何在一个查询中“错误处理”这个问题,而不必在查询之外编写 if else 语句?谢谢 c:
【问题讨论】:
标签: javascript node.js mongodb error-handling