Node.js 如何用新值替换数组,并根据特定字段对其进行排序
假设我的集合中有一个object字段数组,我要做的是用新值替换该数组值,但要按排序Node.js 如何用新值替换数组,并根据特定字段对其进行排序,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,假设我的集合中有一个object字段数组,我要做的是用新值替换该数组值,但要按排序 User.findOneAndUpdate({condition}, { "$set": { "arrayField": arrayValue}}, { multi: true, upsert: true }, function (err, user) { }); 数组中的每个对象都有一个字段索引,其值介于0和1之间。 现在,除了replace操作之外,我想按索引字段的排序顺序插入新值。在更新之前对数组进行排
User.findOneAndUpdate({condition}, { "$set": { "arrayField": arrayValue}}, { multi: true, upsert: true }, function (err, user) {
});
数组中的每个对象都有一个字段索引,其值介于0和1之间。
现在,除了replace操作之外,我想按索引字段的排序顺序插入新值。在更新之前对数组进行排序,mongo将遵守它
arrayValue.sort((a, b) => ...)
您可以通过以下方式实现此结果:
// 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;
});
可以在更新之前对数组进行排序
arrayValue.sort(function(obj1, obj2) {
return obj2.index- obj1.index; // Descending order.
});