I have an object with the following model:
export const Address = mongoose.model('Address',
{
id: mongoose.SchemaTypes.ObjectId,
customer_id: String,
addresses: [{
address_type: String,
address_info: String,
}]
});
An example dataset is like this:
{
"data": {
"address": [
{
"customer_id": "12345123",
"addresses": [
{
"address_type": ANDROID,
"address_info": "dfjghjsdgf"
},
{
"address_type": IOS,
"address_info": "dwrw45345f"
}
]
},
{
"customer_id": "12345124",
"addresses": [
{
"address_type": SMS,
"address_info": "dfjghj231dgf"
},
{
"address_type": IOS,
"address_info": "ww242344234"
}
]
}
]
}
}
It's clear that the addresses field of the Address model is a list, within which each object has two fields : address_type, and address_info.
I wonder how to update an address_info with filters in customer_id and address_type? For example, if I would like to update the ANDROID address of customer_id = 12345123 to abcdefg, it's expected to see the database being updated into :
{
"data": {
"address": [
{
"customer_id": "12345123",
"addresses": [
{
"address_type": ANDROID,
"address_info": "abcdefg"
},
{
"address_type": IOS,
"address_info": "dwrw45345f"
}
]
},
{
"customer_id": "12345124",
"addresses": [
{
"address_type": SMS,
"address_info": "dfjghj231dgf"
},
{
"address_type": IOS,
"address_info": "ww242344234"
}
]
}
]
}
}
Reference: Mongoose :Find and filter nested array
This problem talked about findOne, but I'm more interested in update.
you can try like this
await Address.update(
{ customer_id: "12345123", "addresses.address_type": "ANDROID" },
{$set : { "addresses.$.address_info" : "abcdefg" }}
)