node.js - Update Array Value With Unknown Index Using Mongoose -


this question has answer here:

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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -