const UniversitySchema = new Schema({
university_name: {
type:String,
},
status: {
type: String
}
});
const CollageSchema = new Schema({
collage_name: {
type:String,
required: [true,'Name field is required']
},
university_id: {
type: [{ type: Schema.Types.ObjectId ,
ref: 'university' }]
},
type: {
type:String
}
});
router.delete('/university/:id',function(req,res,next){
University.findByIdAndRemove({_id:req.params.id}).then(function(detail){
res.send(detail);
});
});
我在 CollageSchema
中引用了 UniversitySchema
的 _id
,如果我删除任何大学,相应的拼贴画也应该被删除。这个怎么做?
最佳答案
通过对 collages
集合的额外 mongo 调用,使用 Promise.all() :
router.delete('/university/:id',function(req,res,next){
const ObjectId = require('mongodb').ObjectId;
const _id = ObjectId(req.params.id);
const removeUniversity = University.findByIdAndRemove({ _id: _id });
const removeCollage = Collage.remove({ university_id: _id });
Promise
.all([removeUniversity, removeCollage])
.then(function(values) {
const detail = values[0];
res.send(detail);
})
.catch((err) => console.error(err));
});
关于javascript - 如何删除 Mongoose 模式中的引用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46542337/