I needed to update a mongoose subdocument based on the fields filled out in a form. The update process is working correctly, but I am facing an issue where if any field is left empty in the form, the update deletes those fields in the subdocument. Instead, I want it to only update with the fields provided in the form and leave the rest as they are. Here is the current update function I am using:
List.updateOne(
{"questionSet._id": questId},
{
$set: {
"questionSet.$": req.body
}
},
{new: true, useFindAndModify: false},
(err)=>{
if(err){
console.log(err);
res.redirect("/admin-edit-quest")
} else {
res.redirect("/admin-edit-quest")
}
}
)
Here is an example of my mongoose model structure:
list: { "_id" : ObjectId("60f2cc07275bbb30d8cb268e"),
"listName" : "dsa",
"aboutList" : "dsa queestions",
questionSet" : [ { "solved" : false,
"_id" : ObjectId("60f2cc12275bbb30d8cb2695"),
"topic" : "array",
"name" : "array is best",
"url" : "www.arr.com",
"listname" : "dsa",
"__v" : 0 },
{ "solved" : false,
"_id" : ObjectId("60f2cc1b275bbb30d8cb269d"),
"topic" : "linked list",
"name" : "reverse list",
"url" : "www.list.com",
"listname" : "dsa",
"__v" : 0 }
],
"__v" : 2
}