我试图删除猫鼬数组中的多个对象。我的锻炼模型如下:
{
_id: 5e04068491a2d433007026cd,
exercises: [
{ _id: 5e0401b9dda7ea28a70e99ed, reps: '1', sets: '3' },
{ _id: 5e0401cadda7ea28a70e99ee, reps: '1', sets: '3' },
{ _id: 5e0401dbdda7ea28a70e99ef, reps: '1', sets: '3' }
]
}
我有一个ID数组,名为DeletedExercises,这些是我要从练习列表中删除的对象的ID。我试图遍历DeletedExercise,并删除所有与DeletedExercise项目的ID相匹配的练习。
router.put("/:workoutId", (req, res)=>{
deletedOnes = req.body.exerciseId
deletedExercises = []
if(typeof deletedOnes === 'object'){
deletedOnes.forEach(item => {
deletedExercises.push(item)
})
} else {
deletedExercises.push(deletedOnes)
}
deletedExercises.forEach(item => {
Workout.findByIdAndUpdate( req.params.workoutId,
{ $pull: { exercises: { _id: item} } } )
});
答案 0 :(得分:1)
您可以使用$in
内的$pull
运算符简单地删除练习,如下所示:
router.put("/:workoutId", (req, res) => {
console.log(req.body.exerciseId); //[ '5e05c5306e964f0a549469b8', '5e05c5306e964f0a549469b6' ]
Workout.findByIdAndUpdate(
req.params.workoutId,
{
$pull: {
exercises: {
_id: {$in: req.body.exerciseId}
}
}
},
{ new: true }
)
.then(doc => {
res.send(doc);
})
.catch(err => {
console.log(err);
res.status(500).send("Error");
});
});
假设我们有3种锻炼方式进行锻炼:
{
"_id": "5e05c5306e964f0a549469b5",
"exercises": [
{
"_id": "5e05c5306e964f0a549469b8",
"reps": 8,
"sets": 4
},
{
"_id": "5e05c5306e964f0a549469b7",
"reps": 10,
"sets": 3
},
{
"_id": "5e05c5306e964f0a549469b6",
"reps": 12,
"sets": 2
}
],
}
如果我们要删除此5e05c5306e964f0a549469b8
锻炼的锻炼5e05c5306e964f0a549469b6
和5e05c5306e964f0a549469b5
,则可以使用该正文发送PUT请求:(URL必须以类似{{1的结尾}})
http://.../5e05c5306e964f0a549469b5
响应将是:
{
"exerciseId": [
"5e05c5306e964f0a549469b8",
"5e05c5306e964f0a549469b6"
]
}
答案 1 :(得分:0)
很难说出您不是在说什么错误,但是从我的猜测来看,您是在将ObjectId
与String
进行比较,请尝试替换此行:
{ $pull: { exercises: { _id: item} } } )
与此:
{ $pull: { exercises: { _id: new ObjectId(item)} } } )
**编辑**
您可能还需要将要搜索的主要ID转换为ObjectId
:
Workout.findByIdAndUpdate( new ObjectId(req.params.workoutId),
{ $pull: { exercises: { _id: new ObjectId(item)} } } )