我想在主题模型中搜索一个id,该模型有一个教师ID数组如下
var Classroom = require('./classroom');
var Teacher = require('./teacher');
var ClassSectionSchema = new Schema({
title : String,
teacher_id : [{type: Schema.Types.ObjectId, ref: 'Teacher'}]
});
我想在删除之前搜索每位老师,但如果老师在班级部分连接我不想删除它,我尝试了以下
router.post('/delete',function(req,res){
var teacher_id= req.body.selected;
Class_section.findOne({teacher_id:teacher_id},function(err,subject){
if(err){
console.log(err);
res.json({status:"error", message :"error occurred"});
return;
}else if(subject){
res.json({status:"error", message:"teacher has class"});
return;
}else{
Teacher.remove({_id:teacher_id},function(err){
if(err){
console.log(err);
res.json({status:"error", message :"error occurred"});
return;
}else{
res.json({status:"success",message: "teacher deleted"});
return;
}
})
}
})
})
以前的代码仅在课程部分有一个教师ID时有效,但如果教师ID中有两个教师,教师会被删除
答案 0 :(得分:1)
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId();
router.post('/delete',function(req,res){
var queryObj = {};
if(req.body.selected){
queryObj.teacher_id = {
$in:[new ObjectId(req.body.selected)]
}
}
Class_section.find(queryObj,function(err,subject){
if(err){
console.log(err);
res.json({status:"error", message :"error occurred"});
return;
}else if(subject.length > 0){
res.json({status:"error", message:"teacher has class"});
return;
}else if(subject.length == 0){
Teacher.remove({_id:teacher_id},function(err){
if(err){
console.log(err);
res.json({status:"error", message :"error occurred"});
return;
}else{
res.json({status:"success",message: "teacher deleted"});
return;
}
})
}
})
})