Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo/Mongoose Invalid atomic update value error

I am trying to write to write an update to a Mongo document using the Mongoose findOneAndUpdate function. Essentially, I have a document that has an array of another Schema in it, and when I attempt to append more of those schema type, I get the following error:

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

I'm having a hard time figuring out what this error even means, much less what its source is.

The data I'm attempting to update is as follows:

{ 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"] } ] }

The only difference is that when I retrieve it, there are three fewer modules, and I append some new ones to the array.

Would love to hear any thoughts, at least as to what the error means!

like image 408
user2585019 Avatar asked Jul 15 '13 20:07

user2585019


3 Answers

@Magrelo and @plus led me to an answer that worked. Something like:

MyModel.findOneAndUpdate({ section_id: '51e427ac550dabbb0900000d' }, mongooseObject.toObject(), { upsert: true }, function(err, results) {
    //...
});
like image 182
Shawn Miller Avatar answered Oct 03 '22 08:10

Shawn Miller


This is probably because the updated object is still a Mongoose object. Try to convert it to a JS object before the findOneAndUpdate

object = object.toString()

And delete any potential ID attribute

delete object._id

Or simply

object = object.toObject();
like image 15
Magrelo Avatar answered Nov 16 '22 15:11

Magrelo


I had the same problem and it turned out I was using $push incorrectly. I was doing

{$push:thing_to_push}

But it needed to be

{$push:{list_to_push_into:thing_to_push}}
like image 3
Zeke Nierenberg Avatar answered Nov 16 '22 14:11

Zeke Nierenberg