Remove a specific nested object from an array of objects

守給你的承諾、 提交于 2021-01-28 14:17:51

问题


I need to remove a specific object that is nested inside an array of objects.

The following db structure looks like:

imd

I would like to remove one of the teams based on the roomId (to find the specific room) and based on the team approved state. If a team has "approved: false" it needs to be deleted from the array of objects.

I'm using mongoose and came up with the following, but without succes:

     Room.update({"roomId": req.params.roomId},
        {"$pull": { "teams.approved": false } })

screenshot thats shows the correct roomId: img


回答1:


The array name and equality condition should be specified separately like in this example, try:

await Room.update({"roomId": req.params.roomId}, {"$pull": { "teams": { approved: false } } })



回答2:


Room.updateOne({ roomId: req.params.roomId}, {"$pull": { "teams": { approved: false } } })

This might work for your case.




回答3:


I think something like this should work:

Room.find({roomId: 1234}).then((result) => {
if (result) {
 return Room.remove({result.teams.approved: false})
 } 
} ).catch()

You still need to first find all results matching the roomId number and then removing the teams based on approved. There are probably better ways to handle this but I think it's a fair approach.



来源:https://stackoverflow.com/questions/56664906/remove-a-specific-nested-object-from-an-array-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!