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"
}
You can create a complete update object outside based on the details entered by user & then update values in your query like this
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');
var updateObj = {'todos.$.title': req.body.title, 'todos.$.description': req.body.description, 'todos.$.priority': req.body.priority};
collection.updateOne({_id: mongo.ObjectID(req.params.id),
todos: {$elemMatch: {_id: mongo.ObjectID(req.params.todo_id)}}
},{
$set: updateObj
},function(err, results) {
if (err){
console.log(err);
res.send('');
return
}
res.send(results)
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.