errmsg: '不支持的投影选项:$push: { ... }', code: 2, codeName: 'BadValue' }

Joe*_*lph 3 javascript mongoose mongodb node.js

我在调试这个错误时遇到问题你能帮我吗?

这是我的代码

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);
        }
    )
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

errmsg: '不支持的投影选项: $push: { team: { team_name: “hahaha” } }', code: 2, codeName: 'BadValue' }

chr*_*dam 7

由于错误状态,findOne()方法将文档{ "$push": { "team": { "team_name": req.body.team_name } } }视为投影,并且在投影字段名​​称不以$. 我相信您想做的是更新操作,而不是查询。在这种情况下,您需要使用findOneAndUpdate()orfindByIdAndUpdate()方法,因为该$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);
        }
    )
});
Run Code Online (Sandbox Code Playgroud)

注意findByIdAndUpdate(id, ...)相当于findOneAndUpdate({ _id: id }, ...)