javascript - errmsg : 'Unsupported projection option: $push: { ... }' , 代码 : 2, codeName: 'BadValue' }

标签 javascript node.js mongodb mongoose

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

这是我的代码

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/

相关文章:

java - Morphia @Version 不工作

Java Mongodb 更新数据库对象

javascript - 使用 Android 应用程序运行 HTML5 网站 - 未响应消息

javascript - 关闭带有大量标记的雅虎 map 时避免挂起

node.js - 在不重建和重新启动的情况下 react 更改文件

node.js - 网络实时分析仪表板 : which technologies should use?( Node/django、cassandra/mongodb ...)

Node.js 和 TeamCity

javascript - javascript函数之间的循环引用

JavaScript 右移负数

arrays - MongoDB/NodeJS : Looping through query parameter