我已经定义了一个架构
递归树结构
在里面
这很有效。每个节点都有一个子节点数组,这些子节点引用同一树和架构中的子节点。通过子级的递归,树可以变得很深。
我想用猫鼬
到
递归删除子级(及其所有子级)
,当我用其他Mongoose调用删除它们的父节点时。
在.pre函数中哪个猫鼬先调用发出?
如何妥善处理孩子们的阵势?
注意:如日志所示,我下面代码中当前的deletemony至少将其放入该函数的内部,但可能仍然是错误的。。。。
在.pre的末尾调用什么,以使其正确工作?
1) 等待鲍斯托夫。移除({});-->这将在测试开始时清空我的数据库,并导致.pre代码出现错误“baustoff(remove)is not a function at runtime”
// baustoff.model.js
const mongoose = require('mongoose');
const Baustoffe = require('./../../baustoffe'); // for some enums, irrelevant for BaustoffSchema.pre('remove', )
const BaumKnotenTypen = require('./../../baumknotentypen'); // for some enums, irrelevant for BaustoffSchema.pre('remove', )
const VerzweigungsTypen = require('./../../verzweigungstypen'); // for some enums, irrelevant for BaustoffSchema.pre('remove', )
const MaterialEigenschaftSchema = require('./materialeigenschaft.model.js').model('MaterialEigenschaft').schema
const Schema = mongoose.Schema;
let BaustoffSchema = new Schema
({
// First some normal properties in my BaustoffSchema schema:
kurzBezeichnung: { type: String },
bezeichnung: { type: String, enum: Object.values(Baustoffe) },
baumKnotenTyp: { type: String, enum: Object.values(BaumKnotenTypen) },
verzweigungsTyp: { type: String, enum: Object.values(VerzweigungsTypen)},
aktiv: { type: Boolean, default: true},
produkt: {type: String},
materialEigenschaften: [MaterialEigenschaftSchema], // some properties as an array to allow variable number of props
/*--------------------------------------------------------------------*/
// Now an array of references to children that make up a tree structure, as they refer recursively to the model 'Baustoff'
kinder: [{ type: Schema.Types.ObjectId, ref: 'Baustoff' }],
},
{}
);
Object.assign(BaustoffSchema.statics, {Baustoffe},{BaumKnotenTypen},{VerzweigungsTypen} );
// Above line is to define some statics, irrelevant for the .pre function
/*--------------------------------------------------------------------*/
// PROBLEMATIC PART starts here:
// Goal: Define a Mongoose BaustoffSchema.pre() hook that recursively deletes all children further down in the tree, when their parent is deleted
BaustoffSchema.pre('remove', {query: true}, function(next){
mongoose.models["Baustoff"].deleteMany({ kinder: this._id }, function(err, baustoff) {
console.log("In Mongoose pre Hook before if");
if(baustoff) {
console.log("In Mongoose pre Hook after if");
baustoff.remove(); // ERROR is thrown HERE with this variant of the code: baustoff.remove is not a function at runtime !!!!!!!!!!
});
next();
}); // end of .pre hook
let Baustoff = mongoose.model('Baustoff', BaustoffSchema, 'Baustoffe'); // Model Name, Schema Name, Collection Name in Mongo db
module.exports = Baustoff; // Baustoff is model name hook