在这个问题上被困了几个小时。下面的代码:
router.route("/contact")
.get(function(req,res){
var response = {};
Contact.find({},function(err,data){
if(err) {
response = {"error" : "Error fetching data"};
} else {
response = {"message" : data};
}
res.json(response);
});
})
以上查询生成包含数据库中所有联系人的结果,但是
router.route("/contact/department/:dept")
.get(function(req,res){
var response = {};
var arrDept = req.params.dept.split(",");
if(arrDept.length == 0){
response = {"error": " Please enter Department keywords"};
}
else{
response = {};
arrDept.forEach(function(currentValue){
Video.find({dept: '/'+currentValue+'/i'}, function(err, data){
if(err){
response[currentValue] = "No data found";
}else{
response[currentValue] = data;
}
});
});
}
res.json(response);
});
此代码不会产生任何输出。
代码正在 else block 中进入 forEach 循环,但即使我将查询修改为基本查询,查询也不会生成任何结果
Video.find({},function(err, data){
if(err){
response[currentValue] = "No data found";
}else{
response[currentValue] = data;
}
});
响应 JSON 仍然返回空白。
PS:问题已被简化,因为这只是我在代码中面临的实际问题的一个示例。 找到答案后更新。
最佳答案
res.json(response)
是在查询之外编写的,这就是返回空白 json 的原因。上述场景可以使用 Promise 来解决,如下所示:
var promise = Contact.find({ dept: { $in: arrayDept }}).exec();
promise.then(function(resultJson) { res.json(resultJson); });
这可用于执行数组中的所有查询并返回完整的 json。
关于node.js - Node JS mongoose 查询不产生结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280412/