I have 2 models: Commitments and Users. The Users model has a property named commitments whose value is an array of ObjectIds and reference is the Commitments collection:
const modelName = 'users';
const schema = new mongoose.Schema<UserProperties, UsersModel, UserVirtuals>({
(...)
commitments: {
type: [
{
type: mongoose.SchemaTypes.ObjectId,
ref: 'commitments',
},
],
required: true,
default: [],
},
}, {
collection: modelName,
}).loadClass(User);
The Commitments model has a property named owner whose value is an ObjectId that references a document from the Users model's collection:
const modelName = 'commitments';
const schema = new mongoose.Schema<CommitmentProperties, CommitmentsModel, CommitmentVirtuals>({
(...)
owner: {
type: mongoose.SchemaTypes.ObjectId,
required: true,
},
}, {
collection: modelName,
}).loadClass(Commitment);
I wanted to make it so whenever I deleted a document from the Commitments model's collection, it would also remove the ObjectId of that document from the Users model document of ObjectId owner's commitments property. So, in my Commitments model's schema:
schema.pre('deleteOne', async function() {
(<UsersModel>storage.models.get('users')).findOneAndUpdate({
_id: this.owner,
}, {
$pull: {
commitments: this._id,
},
}).exec().catch(reason => {
logger.log({
category: LoggingCategories.MIDDLEWARE,
type: LoggingType.ERROR,
message: reason,
extraInfo: 'COULD NOT REMOVE COMMITMENT FROM ARRAY OF USER COMMITMENTS',
});
});
});
However this is not working. I don't get any errors and I'm sure that the middleware function is getting executed because I tried logging something within it to test and it did log.