使用Mongoose更新具有未知索引的数组值

时间:2016-05-28 16:12:29

标签: node.js mongodb mongoose

如何查询和更新数组中的值但该值的索引未知且数组是对象的已知键?例如:

doc: {
    _id: 1,
    stripe: {

        // need to update value with ID 2, but do not know the index
        accounts: [{name: 'value1' id: 1}, {name: 'value2', id: 2}]
    }
}

我不确定要执行此操作的运算符/查询。

使用_id 1>>查找文档在doc.stripe.accounts>>中找到ID为2的帐户更新ID为2的帐户

这就是我现在所做的,有效,但我知道有更好的方法。我通过_id查询doc,然后找到我要更新的帐户的索引,然后完全替换条带值。

let obj = doc.stripe.accounts.find(item => {
    return item.id === params.externalAccountId;
});

let index = doc.stripe.accounts.indexOf(obj);

let arr = doc.stripe.accounts.slice();

arr[index] = item;

doc.stripe = Object.assign({}, doc.stripe, { accounts: arr });

doc.save((err, doc) => {
    callback(null, doc.stripe);
});

1 个答案:

答案 0 :(得分:0)

你不需要意大利面条代码,obj是对数组中项目的引用,这意味着如果它发生变化,数组值也会改变

// get account by id
let obj = doc.stripe.accounts.find(item => {
    return item.id === params.externalAccountId;
});

// set account new value
obj.value = 'new value';

// update account
doc.save((err, doc) => {
    callback(null, doc.stripe);
});

// same as above, but more focused on property
doc.update({
    $set: {
        'stripe.accounts': doc.stripe.accounts
    }
}, (err, doc) => {
    callback(null, doc.stripe);
});