node.js - Update Array Value With Unknown Index Using Mongoose -
this question has answer here:
- update array object based on id? 2 answers
how query , update value in array index of value unknown , array known key of object? example:
doc: { _id: 1, stripe: { // need update value id 2, not know index accounts: [{name: 'value1' id: 1}, {name: 'value2', id: 2}] } }
i'm not sure of operator/query this.
find doc _id 1 >> find account id 2 in doc.stripe.accounts >> update account id 2
this doing now, works, know there better way. querying doc _id , finding index of account want update , replacing stripe value.
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); });
you don't need spaghetti code, obj
reference item in array, means if changes, array value change
// account 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 above, more focused on property doc.update({ $set: { 'stripe.accounts': doc.stripe.accounts } }, (err, doc) => { callback(null, doc.stripe); });
Comments
Post a Comment