There are so many questions and answers regarding this subject but why not make it simple.
Branch schema
const Branch = new Schema({
name: { Type: String },
address: {
houseNumber: { Type: String },
street: { Type: String },
city: { Type: String }
}
})
Client schema
const Client = new Schema({
...,
...,
branches: [ branch ] // BRANCH SCHEMA IS SUB DOCUMENTED HERE
})
I know how to $push
and $pull
branch from branches
array.
What I need is to UPDATE the ENTIRE branch object inside branches array, NOT JUST ONE FIELD like I found in so many answers and YES I would like to have back the modified document.
let clientId = req.body.clientId;
let branch = req.body.branch;
Client
.findOneAndUpdate(
{
"_id": clientId,
"branches._id": branch._id
},
{
OPTION 1 // MODIFIED ONLY THE FIRST ITEM (object) IN THE ARRAY
"$set:" { "branches.$": { branch } }
OPTION 2 // MODIFIED EVERY ITEM (object) IN THE ARRAY
"$set:" { "branches.$[]": { branch } }
STILL NO GOOD... HOW TO SOLVE THIS ??
}
)
.then(client => {
WHAT SHOULD I DO HERE IN ORDER TO UPDATE AN ENTIRE BRANCH ??
})
.catch(e => console.log(`error Client.findOne() ${e}`))