Reputation: 1453
Suppose I have an array of object field inside my collection, what I want to do is replace that array values with new values but in sorted order.
User.findOneAndUpdate({condition}, { "$set": { "arrayField": arrayValue}}, { multi: true, upsert: true }, function (err, user) {
});
each object inside array has a field index
that its value is between 0, and 1.
Now beside the replace operation, I want to insert the new value in sorted order by index
field.
Upvotes: 0
Views: 46
Reputation: 1061
Can sort array before update.
arrayValue.sort(function(obj1, obj2) {
return obj2.index- obj1.index; // Descending order.
});
Upvotes: 1
Reputation: 434
you could achieve this result in next way:
// sort + map: easy to read but not so efficient.
// looks like the same logic could be done with reduce and some extra computation
return array.sort(...).map((item, index) => {
item.index = index;
return item;
});
Upvotes: 0
Reputation: 490
Sort the array before updating and mongo will honour it.
arrayValue.sort((a, b) => ...)
Upvotes: 0