更新 mongodb 上的深度数据数组



我正在尝试将一个对象推送到下面的深度嵌套checklist数组:

{
// User
_id : "id",
days : [
{
_id : "id"
day : "6",
tasks: [
{
_id : "id",
name : "todo"
types : {
checklist : [] // i want to push objects here
notes : []
}
},
....
]
},
....
]
}

这是我尝试过但失败了...我的猜测是,$操作员不应该在那个位置:

User.update({_id : user._id , "days.tasks.name": 'todo' } ,{ $push : { 'days.tasks.$.types.checklist' : { data : 'hello World' } }})

或者你可以重新设计你的数据库,并制作一些子模型,用ObjectId引用。

我找到了解决方案,基本上使用唯一id查找特定任务的索引:

router.patch('/user/updatetask', auth , async (req,res)=>{
const user = req.user
const dayIndex = user.days.indexOf(user.days.find(day => day.day == req.body.day))
const taskIndex = user.days[dayIndex].tasks.indexOf(user.days[dayIndex].tasks.find(task => task._id == req.body.task_id))
var obj = {}
obj[`days.${dayIndex}.tasks.${taskIndex}.types.checklist`] = 'no'
try {
await  User.updateOne({_id : user._id } ,{ $push :obj})
res.status(201).send(user)
} catch(e) {
res.status(400).send(e)
}
})

最新更新