Mongoose删除带引用的文档

时间:2017-10-24 13:05:10

标签: node.js mongodb

我有两个SchemaseventSchemapersonSchema,如下所示:

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

1 个答案:

答案 0 :(得分:2)

使用mongoose,您可以在模式中使用prepost middleware

personSchema.post('remove', removeLinkedDocuments);

然后在removeLinkedDocuments回调中,您可以删除所有链接的文档:

function removeLinkedDocuments(doc) {
    // doc will be the removed Person document
    Event.remove({_id: { $in: doc.eventsAttended }})
}

请注意,仅针对以下方法调用中间件(有关详细信息,请参阅链接文档):

  • 计数
  • 找到
  • findOne
  • findOneAndRemove
  • findOneAndUpdate
  • 更新

要在回调中“手动”删除文档,您可以

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) => {
       ...
    })
})