Here is an example of my collection “messages”.
{[
_id: xxx,
shipment: {
_id: xxx
},
messages: [
{
_id: 123,
origin: 'driver'
isRead: false,
...
},
{
_id: 234,
origin: 'driver'
isRead: false,
...
},
{
_id: 345,
origin: 'driver'
isRead: true,
...
},
{
_id: 456,
origin: 'dispatch'
isRead: false,
...
},
]
]}
I’m updating the array objects using the following code which works great, however this returns the entire document back with all array objects, and I need to return a list of only the objects that were updated so I can pull a list of their IDs.
const message = await MessageModel.findOneAndUpdate(
{
_id: messageId
},
{
$set: {
'messages.$[elem].isRead': true
}
},
{
arrayFilters: [{
'elem.isRead': false,
'elem.origin': 'driver'
}],
new: true
}
);
Output I need in some form so I can grab the IDs that were updated to process further:
messages: [
{
_id: 123,
origin: 'driver'
isRead: true,
...
},
{
_id: 234,
origin: 'driver'
isRead: true,
...
}
]
const ids = [123,234];
I understand it’s returning the entire document, but I can’t figure out the best route to grab only what’s updated without doing multiple queries and comparing.
I tried working with aggregate but am new to that and can’t figure it out.
Any help greatly appreciated on the best route.