I am using mongoose 6.1.5.
I have a collection containing multiple types of related documents. Here is parameter-descriptor-item.model.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
/** @summary The schema for a parameter item */
const itemSchema = new Schema({
_id: String,
name: Object,
});
itemSchema.pre(/^find/, function () {
// eslint-disable-next-line no-console
console.log('item pre hit');
});
/** @summary The base model for all parameter items */
module.exports = mongoose.model('Parameters', itemSchema);
ParameterDescriptor
model inherits from ParameterDescriptorItem
. Here is parameter-descriptor.model.js
const mongoose = require('mongoose');
const ParameterDescriptorItem = require('./parameter-descriptor-item.model');
const { Schema } = mongoose;
/** @summary The schema for additional fields for a project */
const parameterSchema = new Schema({
direction: {
type: String,
enum: ['in', 'out'],
required: true,
},
default: {
type: Number,
required: true,
},
min: {
type: Number,
required: false,
},
max: {
type: Number,
required: false,
},
unit: {
type: String,
required: false,
},
});
parameterSchema.pre(/^find/, function () {
// eslint-disable-next-line no-console
console.log('parameter pre hit');
});
/** @summary The model for a parameter descriptor */
module.exports = ParameterDescriptorItem.discriminator('Parameter', parameterSchema);
And here is code to test the use of pre
hooks.
const ParameterDescriptorItem = require('./parameter-descriptor-item.model');
const ParameterDescriptor = require('./parameter-descriptor.model');
await ParameterDescriptorItem.find();
// console shows: 'item pre hit'
await ParameterDescriptor.find();
// there is nothing additional in the console. Neither the 'pre' hooks from
// ParameterDescriptorItem or ParameterDescriptor is called.
This is a significant issue for me. Is there a way to address it? Is there a way to add pre and post hooks to models created with Model.discriminator?