如何查询和更新数组中的值,但该值的索引未知且数组是对象的已知键?例如:
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查询文档,然后找到我要更新的帐户的索引,然后完全替换条带值。
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);
});
你不需要意大利面条代码,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);
});