首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Mongoose pre remove -递归地嵌套到同一模型的引用

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

Stack Overflow用户
提问于 2015-08-10 02:48:51
回答 1查看 508关注 0票数 0

我有一个理论上可以无限嵌套的模型(尽管情况不会是这样)。然而,当我需要删除整个“路径”和它的孩子,以及它的孩子,等等时,它都工作得很好。模型上的"pre remove“只覆盖了第一层关系。当子对象被移除时,看起来"pre remove“不会触发。以下是模型,任何帮助都将不胜感激:

代码语言:javascript
运行
复制
'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);

EN

回答 1

Stack Overflow用户

发布于 2015-08-10 03:03:03

我通过更多的搜索找到了它。我不认为这是一个理想的解决方案,但它目前是有效的。如果有人有更好的方法,如果可能的话,我很乐意减少电话。谢谢!

代码语言:javascript
运行
复制
PathSchema.pre('remove', function(next){
	mongoose.models["Path"].findOneAndRemove({'parent': this._id}, function(err, path) {
		if(path) {
			path.remove();
		}
	});
    next();
});

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31907680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档