I have a similar situation where I have main category such as:
{
"service": {
"isReviewed": false,
"_id": "5ea36b27d7ae560845afb88d",
"mainCategory": "message ",
"SubCategory": [
{
"priceChanged": true,
"_id": "5ea36b27d7ae560845afb88e",
"subCatPrice": "26",
"subCatName": "mustach trimming"
}
],
"shopName": "paddy the barber",
"user": "5ea1fd5b69512dc72ad2f48c",
"date_created": "2020-04-24T22:41:43.368Z",
"__v": 5
}
}
Now, it took a while figure out how to update one piece of the subdocument. as the sub doc is store as an object.
So All id, is first I check the _id of the doc when its passed through the put/:id.
Then, I checked the owner of doc against the req.user.
if everything okay, I looped through the array then I produced a new object.
Then, all I did, is I check each req.body for price or name, if there is a new price, I would just update the price value in the object. if there is new value then the object remains the same.
then all I said, service.SubCategory = newObject and store the data.
Its working fine, however, I ran into the problem of subdoc _id getting updated, so I fixed that by keeping the old value as its.
Now, in terms of performance and optimization, I am not entirely sure if this is the correct way but its working and if they're better away I am willing to change.
Here is the code:
const newObject = {
subCatPrice: "",
subCatName: "",
_id: "",
priceChanged: false
};
let oldDetails = service.SubCategory;
for (const old of oldDetails) {
newObject.subCatPrice = old.subCatPrice;
newObject.subCatName = old.subCatName;
newObject._id = old._id;
}
price ? (newObject.subCatPrice = price ) && (newObject.priceChanged = true) : newObject.subCatPrice;
name ? (newObject.subCatName = name) : newObject.subCatName;
(service.SubCategory = newObject), await service.save();
I used the react idea of the state to be honest, where I just get a copy of the object and keep it and apply an update to the piece that I want to update.
Again in terms of clean code and all of that stuff, I am not sure if this is the correct way to do it, but I am also a student of programming and I would like to learn too.
Hope this help someone