我们如何用新值替换数组,并根据特定字段对它们进行排序

时间:2018-10-22 06:29:04

标签: node.js mongodb mongoose

假设我的收藏夹中有一个对象字段数组,我想要做的是用新值替换该数组值,但按排序顺序。

User.findOneAndUpdate({condition}, { "$set": { "arrayField": arrayValue}}, { multi: true, upsert: true }, function (err, user) {

});

数组中的每个对象都有一个字段index,其值在0到1之间。 现在,在替换操作旁边,我想按index字段的排序顺序插入新值。

3 个答案:

答案 0 :(得分:1)

可以在更新之前对数组进行排序。

complete

答案 1 :(得分:0)

在更新之前对数组进行排序,mongo会尊重它。

RewriteCond %{REQUEST_URI} ^/OAuth$
RewrtieCond %{QUERY_STRING} ^code=(.*)&state=(.*)$
RewriteRule ^(.*)$ /index.php?slug=$1&code=%1&state=%2

答案 2 :(得分:0)

您可以通过以下方式实现此结果:

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