简体   繁体   中英

how to dynamically update embedded document with $set in mongoose

Im trying to create a function that changes the value of an embedded MongoDB document (contained in an array) with a given position.

removeAddress(accountNumber, position) {
    const remove = Account.findOneAndUpdate({ accountNumber: accountNumber }, { $set: { `mailingAddress.${position}.active`: false } })

    return Promise.resolve(remove);
}

Iv tried using es6 string interpolation mailingAddress.${position}.active and "mailingAddress." + position + ".active" "mailingAddress." + position + ".active" but neither work.

Any ideas?

Build the setter dynamically :

var setter = { $set: {} };
setter.$set["mailingAddress." + position + ".active"] = false;

const remove = Account.findOneAndUpdate({
    accountNumber: accountNumber
}, setter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM