【问题标题】:Mongoose delete nested subdocuments and documentsMongoose 删除嵌套的子文档和文档
【发布时间】:2017-04-27 19:23:39
【问题描述】:

我有:

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

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我建议批量获取对象 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);
    });
    

    这将从类别中删除该广告,并从其广告数组中包含该广告的用户中删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2016-11-09
      • 2019-07-16
      相关资源
      最近更新 更多