Mongoose删除嵌套的子文档和文档

时间:2017-04-27 09:12:16

标签: mongodb mongoose

我有:

    let userSchema = mongoose.Schema({
email: {type: String, required: true, unique: true},
passwordHash: {type: String, required: true},
fullName: {type: String, required: true},
salt: {type: String, required: true},
ads: [{type: ObjectId, ref: 'Ad'}],
roles: [{type: String}]

}

let adSchema = mongoose.Schema({
author: {type: ObjectId, ref: 'User'},
title: {type: String, required: true},
category: {type: ObjectId, ref: 'Category', required: true},
town: {type: ObjectId, ref: 'Town', required: true},

} );

let categorySchema = mongoose.Schema({
name: {type: String, required: true, unique: true},
ads: [{type: ObjectId, ref: 'Ad'}]

} );

let townSchema = mongoose.Schema({
name: {type: String, required: true, unique: true},
ads: [{type: ObjectId, ref: 'Ad'}]

} );

我想通过ID找到例如城镇,并删除其中的所有广告(以及从其类别和作者中删除广告)。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我建议批量获取对象ID数组,然后像这样使用它:

Ad.remove({_id: {$in: Ad_ids_array}}, function(){...}); // and so on

您可以在广告架构定义中添加预删除挂钩,如下所示:

adSchema.pre('remove', function(next) {
  let lethis = this;
  // Pull ad out of all the Category docs that reference the removed ad.
  this.model('Category').update({}, { $pull: {ads: lethis._id}}, { safe: true }, next);

  // Pull ad out of all the User docs that reference the removed ad.
  this.model('User').update({}, { $pull: {ads: lethis._id}}, { safe: true }, next);
});

这会从广告数组中包含广告的类别和用户中删除广告。