Mongo / Mongoose无效的原子更新值错误

时间:2013-07-15 20:51:15

标签: node.js mongodb mongoose database

我正在尝试编写使用Mongoose findOneAndUpdate函数编写Mongo文档的更新。本质上,我有一个文档,其中包含另一个Schema数组,当我尝试追加更多这些模式类型时,我收到以下错误:

[Error: Invalid atomic update value for $__. Expected an object, received object]

我很难弄清楚这个错误甚至意味着什么,更不用说它的来源了。

我正在尝试更新的数据如下:

{ section_id: 51e427ac550dabbb0900000d,
version_id: 7,
last_editor_id: 51ca0c4b5b0669307000000e,
changelog: 'Added modules via merge function.',
committed: true,
_id: 51e45c559b85903d0f00000a,
__v: 0,
modules: 
[ { orderId: 0,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] },
{ orderId: 1,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] },
{ orderId: 2,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] },
{ orderId: 3,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] },
{ orderId: 4,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] },
{ orderId: 5,
type: 'test',
tags: [],
data: [],
images: [],
content: ["Some Content Here"] } ] }

唯一的区别是,当我检索它时,有三个较少的模块,我将一些新的模块添加到数组中。

很想听到任何想法,至少是错误意味着什么!

6 个答案:

答案 0 :(得分:12)

这可能是因为更新的对象仍然是Mongoose对象。 尝试在findOneAndUpdate

之前将其转换为JS对象
object = object.toString()

并删除任何潜在的ID属性

delete object._id

或者只是

object = object.toObject();

答案 1 :(得分:3)

我遇到了同样的问题,事实证明我正在使用$ push错误。我在做什么

{$push:thing_to_push}

但它必须是

{$push:{list_to_push_into:thing_to_push}}

答案 2 :(得分:2)

@Magrelo和@plus让我得到了一个有效的答案。类似的东西:

MyModel.findOneAndUpdate({ section_id: '51e427ac550dabbb0900000d' }, mongooseObject.toObject(), { upsert: true }, function(err, results) {
    //...
});

答案 3 :(得分:1)

尝试将update参数值作为字符串而不是mongoose模型对象传递。当我用来传递模型对象时,我得到了同样的错误。以下是代码差异。

有问题的代码:

updateUser: function(req, res) {
**var updatedUserModel = new Users(req.body);**
    Users.findOneAndUpdate({tpx_id:req.params.id}, {$set:**updatedUserModel**}, function(err, User){
           ...
   }
}

工作代码:

updateUser: function(req, res) {
   Users.findOneAndUpdate({tpx_id:req.params.id}, {$set:**req.body**}, function(err, User) {
   ...
}

答案 4 :(得分:0)

我有同样的问题。我最后使用finOne() method

如果找不到,则创建一个新的,如果找到则更新现有的。

我知道有两个操作。但我只是没有找到任何办法一步到位。

答案 5 :(得分:0)

要检查的另一件事是你是否正在向$ set发送一系列更改。在调用这样的内容时收到的错误消息:

db.products.update( { sku: "abc123" },
                { $set: [
                         {quantity: 500},
                         {instock: true}
                        ]
                }
              )

给我[错误:$ set的原子更新值无效。期待一个对象,收到对象]

将其更改为对象。

db.products.update( { sku: "abc123" },
                { $set: {
                          quantity: 500,
                          instock: true
                        }
                }
              )