1

I have a user model with the following schema

{
  _id: userId,
  inbox: {
    inbox: [Array of message documents],
    sent: [Array of message documents],
  }
}

Is there a way to get only the updated subdocument after an update in mongodb / mongoose ?

The update is good i just want to return the updated subdocument instead of querying the db again

db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 } <-- how to return only the subdocument like in a query
);

expected output the array at inbox.sent with only the updated doc

{
  _id: userId,
  inbox: {
    sent: [{ updated doc}]
  }  
}
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • How does your schema look like? And what expected output you want after update? – Ashh May 26 '19 at 12:12
  • @Fanpark I know you can select fields but because it is an array i will get the full length array and i will need to iterate over it to find the sub document. is there a way to get an array with a single element like if we do `db.getCollection("users").findOne( { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") }, { "inbox.sent.$": 1 } )` – Asaf Aviv May 26 '19 at 12:28
  • Please check both duplicate answer. One will explain your how can you project in findOneAndUpdate and another will show you how positional operator can help to project array elements. – Ashh May 26 '19 at 12:31

1 Answers1

0

You need to apply a callback to the findOneAndUpdate function

e.g:

db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 },
  function (err, res) {
    //here you have the res, which will be the affected record
  }
);
sassy_rog
  • 1,077
  • 12
  • 30
  • I know that you need to provide a `cb`, the update returns the entire document with the entire `inbox.sent` array – Asaf Aviv May 26 '19 at 12:23
  • Unfortunately the is no other way with the `findOneAndUpdate` function to target specific areas of the the record. Do you want just the updated part of the array? – sassy_rog May 26 '19 at 12:27