errmsg:'不支持的投影选项:$ push:{…}',代码:2,codeName:'BadValue'}

我有debugging这个错误的问题,你能帮我吗?

这是我的代码

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:'不支持的投影选项:$ push:{team:{team_name:“hahaha”}}“,代码: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 }, ...)