一直困住这个问题几个小时。下面的代码:节点JS mongoose查询不生成结果
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块foreach循环,但查询不产生任何结果,即使我修改查询到一个基本的像
Video.find({},function(err, data){
if(err){
response[currentValue] = "No data found";
}else{
response[currentValue] = data;
}
});
JSON仍会返回空白的响应。
PS:问题已被简化,因为这只是我在代码中遇到的实际问题的一个示例。找到答案后更新 。
感谢DAXaholic ....但我如何追加数据从循环的每个迭代到响应json对象? –
要做到这一点,没有任何进一步的助手库,你可以例如使用结果在回调之外维护一个数组,并在回调中添加它,只要该数组的大小等于您的'arrDept',就知道您已获得所有结果。但说实话,使用诸如async.js之类的东西更容易和直接。有关我的意思的快速示例,请参阅https://github.com/caolan/async#map。 – DAXaholic
thnx ...我终于用诺言解决了它。 var promise = Contact.find({dept:{$ in:arrayDept}})。exec(); \t \t \t promise.then(函数(resultJson){ \t \t \t \t res.json(resultJson); \t \t \t}); –