Mongoose pre remove - 递归地对同一模型的嵌套引用

时间:2015-08-09 18:48:51

标签: node.js mongodb recursion mongoose

我有一个理论上可以无限嵌套的模型(虽然情况永远不会如此)。然而,当我需要删除整个"路径时,这一切都很有效。及其子女及其子女等... ...在模型上,只涵盖第一层关系。当孩子被移除时,它会出现" 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);




1 个答案:

答案 0 :(得分:0)

我想通过多搜索来解决这个问题。我不认为它是一个理想的解决方案,但它现在有效。如果有人有更好的方法,我希望尽可能减少通话。谢谢!



PathSchema.pre('remove', function(next){
	mongoose.models["Path"].findOneAndRemove({'parent': this._id}, function(err, path) {
		if(path) {
			path.remove();
		}
	});
    next();
});