我有一个理论上可以无限嵌套的模型(尽管情况不会是这样)。然而,当我需要删除整个“路径”和它的孩子,以及它的孩子,等等时,它都工作得很好。模型上的"pre remove“只覆盖了第一层关系。当子对象被移除时,看起来"pre remove“不会触发。以下是模型,任何帮助都将不胜感激:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Path Schema
*/
var PathSchema = new Schema({
parent: {
type: Schema.ObjectId,
ref: 'Path'
},
field: {
api: {
type: String,
default: '',
trim: true
},
label: {
type: String,
default: '',
trim: true
}
},
match: {
type: String,
default: 'equals',
trim: true
},
value: {
type: String,
default: '',
trim: true
},
date_created: {
type: Date,
default: Date.now
},
date_modified: {
type: Date,
default: Date.now
},
user_created: {
type: Schema.ObjectId,
ref: 'User'
},
user_modified: {
type: Schema.ObjectId,
ref: 'User'
},
});
PathSchema.pre('save', function(next) {
var now = new Date();
this.date_modified = now;
this.user_modified = this.user;
if (!this.date_created) {
this.date_created = now;
}
if (!this.user_created) {
this.user_created = this.user;
}
delete this.user;
next();
});
PathSchema.pre('remove', function(next) {
mongoose.models["Path"].remove({
parent: this._id
}).exec();
next();
});
mongoose.model('Path', PathSchema);
发布于 2015-08-10 03:03:03
我通过更多的搜索找到了它。我不认为这是一个理想的解决方案,但它目前是有效的。如果有人有更好的方法,如果可能的话,我很乐意减少电话。谢谢!
PathSchema.pre('remove', function(next){
mongoose.models["Path"].findOneAndRemove({'parent': this._id}, function(err, path) {
if(path) {
path.remove();
}
});
next();
});
https://stackoverflow.com/questions/31907680
复制相似问题