我将Node / Express与MongoDB结合使用,试图查找是否存在具有特定字段名称的对象。
我认为数据库连接本身还可以,因为我可以将事情添加到数据库中(通过运行应用程序,然后通过mongo shell进行确认)
下面的代码应该使字段student
的值Class
增加1,/nextpage
如果遇到问题,请转到下一页。
exports.join = function(req,res,next){
Class.find(({code:{$in: [req.body.roomNumber]}}), function(err, out){
if(err){res.redirect('/'); next(err);}
else{
console.log(out); // returns the whole object from db.
// for no match, I get "[]"
console.log(req.body.formEntry); // returns the entered form value OK
console.log(out.roomNumber); // always returns "undefined"; why?
if(out != null) { // always passes
console.log('adding 1 to students');
Class.update({code:req.body.formEntry}, {$inc:{'students':1}}); // also didn't work
res.redirect('/nextpage');
}else{
console.log('class not found');
}
}
};
}
我曾尝试检查诸如out.params.roomNumber
(get undefined)或out.next()
(thinking it is a query)之类的东西,但console.log(out.roomNumber)
考虑到这一事实,它console.log(out)
给我所需的对象及其所有字段均完好无损,我对(ALWAYS undefined)的输出感到困惑。我读了一个类似的问题,但是问题在于异步性,因为整件事都在回调中,我认为可能并非如此。
find
返回结果数组,数组也是如此out
。
如果每个班级都有一个唯一的房间号,则使用findOne
更为合理:
Class.findOne({ code : req.body.roomNumber }, function(err, out) {
// `out` is now a single result, provided there was a match
...
});
另外,$in
用于匹配单个房间号有点多余,因此我将其排除在查询之外(类似于您用于的查询update
)。
顺便说一句,你不应该混res.redirect()
和next()
在一起(因为发送重定向结束请求,但next
它传递给其他处理,这将在快速触发错误)。我建议使用此:
if (err) {
return res.redirect('/');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句