0

How do I query and update a value in an array but the index of that value is unknown and the array is a known key of an object? For example:

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}]
    }
}

I'm not sure of the operator/query to do this.

Find doc with _id 1 >> find account with id 2 in doc.stripe.accounts >> update account with id 2

This is what I am doing now, which works, but I know there is a better way. I am querying the doc by _id and then finding the index of the account I want to update and then completely replacing the 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);
});
pizzarob
  • 11,711
  • 6
  • 48
  • 69

1 Answers1

0

You don't need spaghetti code, obj is reference to item in array, which means if it changes, array value also will change

// 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);
});
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69