2017-04-27 80 views
0

我:貓鼬刪除嵌套子文檔和文件

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找到城鎮的例子,並刪除其中的所有廣告(以及從他們的類別和作者中刪除廣告)。我該怎麼做?

回答

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

這將從廣告數組中的類別和用戶中移除廣告。