我有两个Schemas
,eventSchema
和personSchema
,如下所示:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
dob: Date,
city: String,
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
如何从已删除的eventsAttended
中删除所有Person
?
例如,如果我删除了Person
,那么我预计会删除分配给该Person
的所有事件。
这是我的代码:
Person.findOneAndRemove({_id: req.body._id}, (err, response) => {
// remove the events assigned to this person
})
答案 0 :(得分:2)
使用mongoose,您可以在模式中使用pre
和post
middleware:
personSchema.post('remove', removeLinkedDocuments);
然后在removeLinkedDocuments
回调中,您可以删除所有链接的文档:
function removeLinkedDocuments(doc) {
// doc will be the removed Person document
Event.remove({_id: { $in: doc.eventsAttended }})
}
请注意,仅针对以下方法调用中间件(有关详细信息,请参阅链接文档):
要在回调中“手动”删除文档,您可以
Person.findOneAndRemove({_id: req.body._id}, (err, response) => {
// note that if you have populated the Event documents to
// the person documents, you have to extract the id from the
// req.body.eventsAttended object
Event.remove({_id: { $in: req.body.eventsAttended }}, (err, res) => {
...
})
})