Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何用新值替换数组,并根据特定字段对其进行排序_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 如何用新值替换数组,并根据特定字段对其进行排序

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操作之外,我想按索引字段的排序顺序插入新值。在更新之前对数组进行排

假设我的集合中有一个object字段数组,我要做的是用新值替换该数组值,但要按排序

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.
 });