[英]How to Update An Array of Subdocuments on a MongoDB Collection in MeteorJS
[英]How to query and update mongodb subdocuments
所以,我正在嘗試更新 MongoDB 中的一個子文檔,我正在使用 express 並且我有以下路線來查找我想要更新的確切對象,目前我只能用一個新文檔替換整個文檔,可以嗎如果我保持這樣,或者是否有 MongoDB/mongoose 操作/函數可以幫助我根據用戶提供的內容更新字段,例如,如果他們只提供要更新的標題或優先級。 我知道我不必使用模式來更新一個屬性,我試圖找到一種替代方法來使用 if - elseif 或 switch 語句鏈。
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)
});
});
我試圖更新的對象看起來像這樣:
{
_id: "5e3bf72db5074c1e205409f5",
todos: [
{
_id: "5e42bef746bae7728c68384f",
title: "cool title 1",
description: "cool description 2",
priority: 1
}
],
title: "hjskadjshd"
}
您可以根據用戶輸入的詳細信息在外部創建一個完整的更新對象,然后像這樣更新查詢中的值
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)
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.