作为How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?中我的问题的解决方案,我编写了以下代码。
但这会产生错误,指出 TypeError:callback.apply不是函数。我对此并不熟悉。谁能解决这个错误?
码
router.post("/saveMCQAnswer", function(req, res) {
Survey.findOneAndUpdate(
{ "_id": '0001'},
{ "surveyname": 's1' }, /* <query> */
{ /* <update> */
"$push": {
"replies": {
"_id" : 'R001',
"answers": {
"_id" : 'A001',
"answer" : 'answer'
}
}
}
},
{ "upsert": true }, /* <options> */
function(err, doc){ /* <callback> */
if(err) res.json(err);
else
req.flash('success_msg', 'Question saved to QBank');
res.redirect("/");
}
);
});
答案 0 :(得分:3)
您有一个额外的查询参数导致该问题。将其移动到第一个查询对象:
router.post("/saveMCQAnswer", function(req, res) {
Survey.findOneAndUpdate(
{ /* <query> */
"_id": '0001',
"surveyname": 's1' // <-- fix here
},
{ /* <update> */
"$push": {
"replies": {
"_id" : 'R001',
"answers": {
"_id" : 'A001',
"answer" : 'answer'
}
}
}
},
{ "upsert": true }, /* <options> */
function(err, doc){ /* <callback> */
if(err) res.json(err);
else
req.flash('success_msg', 'Question saved to QBank');
res.redirect("/");
}
);
});