我正在尝试删除"挑战中的文档"集合,但仅当用户位于具有管理角色的该挑战的参与者列表中时。
我当前的代码记录challenge deleted
,但实际上并未实现挑战。
以下是挑战模式:
var challengeSchema = mongoose.Schema({
name : {type: String, required: true},
description : {type: String, required: true},
startDate: {type: Date, required: true},
endDate: {type: Date, required: true},
creationDate: {type: Date, required: true},
goalType : {type: String, required: true},
goalAmount: {type: Number, required: true},
participants : {type : [], required: true},
categories : {type: [String], required: true}
});
以下是查询的当前尝试,其中Challenge
是模型变量:
Challenge.findOne({"_id" : req.params.challengeId, "participant" : {
$elemMatch : {participantID : req.user.id, participantRole : "admin"}
}}).remove(function(err, challenge){
if (err){
console.log(err);
res.redirect('/user/dashboard');
}
if (!challenge){
console.log("no challenge found");
res.redirect('/user/dashboard');
}
else {
console.log("challenge deleted");
res.redirect('/user/dashboard');
}
})
答案 0 :(得分:1)
使用findOneAndRemove而不是findOne。 像这样:
Challenge.findOneAndRemove({"_id" : req.params.challengeId, "participant" : {
$elemMatch : {participantID : req.user.id, participantRole : "admin"}
}},function(err, challenge){
if (err){
console.log(err);
res.redirect('/user/dashboard');
}
if (!challenge){
console.log("no challenge found");
res.redirect('/user/dashboard');
}
else {
console.log("challenge deleted");
res.redirect('/user/dashboard');
}
})