I am creating a private npm package to share my MongoDB schemas across multiple projects. I have a parent schema (DeviceSchema) and a child schema (PayloadSchema) that references the parent schema. Here's a simplified version of my schemas:
import mongoose from "mongoose";
const DeviceSchema = new mongoose.Schema({
// other fields...
});
const PayloadSchema = new mongoose.Schema({
device: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Device',
},
// other fields...
});
In my application, I need to perform certain operations when a Device document is removed, such as removing all Payload documents associated with that Device. Normally, I would use Mongoose's middleware functions to handle this, but Mongoose recommends not to use models in the package.
Is there a way to handle these types of operations using only schemas? Or is there a recommended approach for sharing MongoDB schemas that have relationships with each other in a npm package? Any guidance would be appreciated.
I tried using Mongoose's pre-remove middleware in the DeviceSchema as follows:
DeviceSchema.pre('findOneAndDelete', function(next) {
// remove all payloads associated
this.model('Payload').remove({ device: this._id }, next);
});
But this solution is not possible, this.model does not exist.