0

I searched all stackoverflow, but didn't find anything that solves my problem.

This is my mongoose user schema:

name: String,
movies: [new Schema({
  state: String,
  rate: String,
  note: String
})]

For example I want to update note to test in movie with _id: 20 here. But I don't want to send the whole movie object that contains all rate, state and note values.

name: Mehdi,
movies: [
  {
    _id: 10,
    note: 'This is awesome',
    rate: 10
  },
  {
    _id: 20,
    rate: 7
  }
]

This is my current code:
It overwrites the whole movie object.

User.findOneAndUpdate({
  _id: user._id,
  'movies._id': 20
}, {
  $set: {
    'movies.$': movie
  }
}, {
  new: true
})

Should I find and then do it with plain JS and then .save() it?

It's not exact question as MongoDB - Update objects in a document's array (nested updating). Because I don't want to send the whole object. I may just want to send

_id: 10,
state: 'watched'

P.S.
I found this plugin, but it has no workaround for specific object in array.

Mehdi Hoseini
  • 407
  • 1
  • 4
  • 12
  • 1
    So you mean `$set: { 'movies.$.note': 'test' }`. This is what the [documentation does tell you](https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array) to do. – Neil Lunn Oct 22 '17 at 09:34
  • @NeilLunn I don't want to send complete movie object. You say I should do: `'movies.$.note': movie.note, 'movies.$.state': movie.state, 'movies.$.rate' : movie.rate` ? – Mehdi Hoseini Oct 22 '17 at 09:40
  • I say, the documentation says, and the duplicate says that is so. Yes that is the syntax. Name each property via "dot notation" unless your intention is to to actually replace the whole object. – Neil Lunn Oct 22 '17 at 09:53
  • @NeilLunn So I'm not missing anything? there is actually no way that I can just send `{_id: 10, state: ''watched"}` and have an "updated" object? – Mehdi Hoseini Oct 22 '17 at 10:00
  • I think you might be missing quite a bit. Perhaps take a rest from this for a while. Then come back and read the referenced answers and documentation and spend a little time practicing exercises and understanding it. It's pretty simple stuff but you are clearly missing the point. Come back with fresh eyes. – Neil Lunn Oct 22 '17 at 10:04
  • @NeilLunn Man, I'm so confused – Mehdi Hoseini Oct 22 '17 at 15:02

0 Answers0