2017-04-27 4 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); 
}); 

これにより、広告配列内のカテゴリとユーザーから広告が削除されます。

関連する問題