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

use*_*019 11 database mongoose mongodb node.js

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

[Error: Invalid atomic update value for $__. Expected an object, received object]
Run Code Online (Sandbox Code Playgroud)

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

我试图更新的数据如下:

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

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

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

小智 13

这可能是因为更新的对象仍然是Mongoose对象.尝试在之前将其转换为JS对象findOneAndUpdate

object = object.toString()
Run Code Online (Sandbox Code Playgroud)

并删除任何潜在的ID属性

delete object._id
Run Code Online (Sandbox Code Playgroud)

或者干脆

object = object.toObject();
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用.toObject()将mongooseObject转换为对象 (6认同)

Jak*_*Lin 0

我遇到过同样的问题。我最终使用finOne() 方法

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

我知道有两个操作。但我只是没有找到任何方法可以一步完成。