I am facing this problem to update subdocument in order. I have found the approach to update subdocument, even nested subdocument before. but now I have no idea how to update them in the sequence I need.
I need to update the category order in the array sequence sent, example as below
idList = ["5c603101ff83f23868bd9b12", "5c5e901e5e40d32434b6d8a0"];
The document in the collection
I have tried to use for loop which works, but I think there is a better approach instead of updating each subdocument one by one. Hope to get your pieces of advice
for (var i = 0; i < idList.length; i++) {
menus.findOneAndUpdate({
'_id': menuId,
'categoryDetails._id': idList[i],
}, {
$set: {
'categoryDetails.$.order': i
}
}, (err, result) => {
if (err) {
console.log(chalk.red(err));
return res.status(500).json(err)
}
console.log(chalk.green('UPDATE: (Admin) Category order ' + i));
});
}
return res.status(200).json()