我在调试这个错误时遇到了问题,你能帮我吗?
这是我的代码
router.post('/accounts/show_accounts/:id', function(req,res){
Account.findOne(
{_id:req.params.id},
{$push: {team: {team_name: req.body.team_name}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
}
)
});
我收到以下错误
errmsg: 'Unsupported projection option: $push: { team: { team_name: “hahaha” } }', code: 2, codeName: 'BadValue' }
最佳答案
如错误所述, findOne()
方法将文档 { "$push": { "team": { "team_name": req.body.team_name } } }
视为投影,并且在投影字段名称中不以 $
开头。我相信您想进行更新操作,而不是查询。在这种情况下,您需要使用 findOneAndUpdate()
或 findByIdAndUpdate()
方法因为 $push
运算符仅用于更新操作,而不是像 findOne()
这样的查询:
router.post('/accounts/show_accounts/:id', function(req, res){
Account.findByIdAndUpdate(
req.params.id,
{ "$push": { "team": { "team_name": req.body.team_name } } },
{ "upsert": true, "new": true },
function(err, model) {
if (err) throw err;
console.log(model);
}
)
});
注意:findByIdAndUpdate(id, ...)
等价于findOneAndUpdate({ _id: id }, ...)
关于javascript - errmsg : 'Unsupported projection option: $push: { ... }' , 代码 : 2, codeName: 'BadValue' },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41591630/