jones
jones

Reputation: 1453

How we can replace an array with new value, and sort them based on specific field

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

Answers (3)

Mobasher Fasihy
Mobasher Fasihy

Reputation: 1061

Can sort array before update.

 arrayValue.sort(function(obj1, obj2) {
   return obj2.index- obj1.index; // Descending order.
 });

Upvotes: 1

Andrei Piatrou
Andrei Piatrou

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

sofcal
sofcal

Reputation: 490

Sort the array before updating and mongo will honour it.

arrayValue.sort((a, b) => ...)

Upvotes: 0

Related Questions