简体   繁体   中英

How to update multiple array elements with different keys in mongoose

I have document containing lists. For example, the users document looks like:

[
  {
    _id: 1,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
  {
    _id: 2,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
...
]

And I want to update this document with the following data:

updateUserData: {
  _id: 2,
  photos: [{_id:1, size:200}, {_id:2, size:300}]
}

And the result should be:

[
  {
    _id: 1,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
  {
    _id: 2,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 200},
      {_id: 2, url:'https://example.com/2.jpg', size: 300}
    ]
  },
...
]

How can I get this done by using one command in mongoose?

I have document containing lists. For example, the users document looks like:

[
  {
    _id: 1,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
  {
    _id: 2,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
...
]

And I want to update this document with the following data:

updateUserData: {
  _id: 2,
  photos: [{_id:1, size:200}, {_id:2, size:300}]
}

And the result should be:

[
  {
    _id: 1,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 100},
      {_id: 2, url:'https://example.com/2.jpg', size: 123}
    ]
  },
  {
    _id: 2,
    photos: [
      {_id: 1, url:'https://example.com/1.jpg', size: 200},
      {_id: 2, url:'https://example.com/2.jpg', size: 300}
    ]
  },
...
]

How can I get this done by using one command in mongoose?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM