Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update subdocument with findOneAndUpdate?

there is a document in collection books :

{ _id : someMongooseGeneratedId,
  name : 'myBook',
  data : [{_id : 'page', name : 'one'},{ _id : 'chapter', name : 'Chapter One' }]
 }

I want to update books where book name is 'myBook' : Set name of chapter as 'Chapter 1' to the data where _id is 'chapter'

result as :

{ _id : someMongooseGeneratedId,
  name : 'myBook',
  data : [{_id : 'page', name : 'one'},{ _id : 'chapter', name : 'Chapter 1' }]
 }

I am looking to do the same with single query with mongoose.

like image 941
codeofnode Avatar asked Feb 03 '14 07:02

codeofnode


1 Answers

The following works for me :

Model.findOneAndUpdate({ name : 'myBook', "data._id" : 'chapter' }, { "data.$.name" : 'Chapter 1' });
like image 80
codeofnode Avatar answered Sep 21 '22 23:09

codeofnode