节点JSmongoose查询不产生结果
一直困在这个问题上好几个小时。 以下代码:
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块中inputforEach循环,但是即使将查询修改为基本types,查询也不会生成任何结果
Video.find({},function(err, data){ if(err){ response[currentValue] = "No data found"; }else{ response[currentValue] = data; } });
响应JSON仍然返回空白。
PS:问题已被简化,只是我在代码中遇到的实际问题的一个例子。 find答案后更新。
你的res.json(response);
在非工作示例中,在MongoDB查询的callback之外,那就是在查询的callback被实际执行之前,你正在写回应,因此你的结果是空的。
res.json(response)
被写在查询之外,这就是为什么一个空白的JSON得到返回。 上面的情况可以用promise来解决,如下所示:
var promise = Contact.find({ dept: { $in: arrayDept }}).exec(); promise.then(function(resultJson) { res.json(resultJson); });
这可以用来执行数组中的所有查询并返回完整的json。