So, I am trying to update a subdocument in MongoDB, I am using express and I have the below route for finding the exact object I want to update, at the moment I can only replace the whole document with a new one, is it ok if I leave it like this or is there a MongoDB/mongoose operation/function that can help me to just update the fields based on what the user provides, for example, if they just provide a title to be updated or a priority. I know that I have to not use the schema to update just one property, I am trying to find an alternative to using a chain fo if - elseif or switch statements.
app.put('/updateTodoInProject/:id/:todo_id', (req,res)=>{ //':id' represents the id of the project in which the todo is
const collection = db.collection('projects');
const todo = new Todo({title: req.body.title, description: req.body.description, priority: req.body.priority});
collection.updateOne({_id: mongo.ObjectID(req.params.id),
todos: {$elemMatch: {_id: mongo.ObjectID(req.params.todo_id)}}
},{
$set: {
"todos.$": todo
}
},function(err, results) {
if (err){
console.log(err);
res.send('');
return
}
res.send(results)
});
});
The object I am trying to update looks something like this:
{
_id: "5e3bf72db5074c1e205409f5",
todos: [
{
_id: "5e42bef746bae7728c68384f",
title: "cool title 1",
description: "cool description 2",
priority: 1
}
],
title: "hjskadjshd"
}