杂种删除嵌套的子图和文档



我有:

    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查找城镇并删除其中的所有广告(当然是从类别中删除广告和作者的广告(。我该怎么做?

我建议批量获取对象ID的数组并这样使用:

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

您可以在这样的AD模式定义中添加预示例挂钩:

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

这将从其广告数组中的类别和用户中删除广告。

最新更新