如何删除mongoose模式中的引用值

时间:2017-10-03 10:22:13

标签: javascript node.js mongodb mongoose

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);
	});
});

我在_id中引用了UniversitySchema的{​​{1}},如果我删除任何大学,则应删除相应的拼贴。这该怎么做?

1 个答案:

答案 0 :(得分:0)

使用Promise.all()

collages集合上进行额外的mongo调用
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));

});