I have the following schematics:
const ClienteSchema = new Schema({
nombre: {
type: String,
required: [true, "El cliente es requerido"]
}
apellido: {
type: String,
required: [true, "El cliente es requerido"]
}
})
const AlquilerSchema = new Schema({
fecha_pago: {
type: Date,
required: [true, "La fecha de pago es requerida"]
}
cliente: {
type: Schema.Types.ObjectId,
ref: 'Cliente',
required: [true, "El cliente es requerido"]
}
})
What I want to achieve is that when I delete a client, all the rentals made by the client are eliminated atomically.
I found that Mongo Atlas provides a trigger system, I can't use it since my DB is not hosted in Mongo Atlas.
What I did was use the middleware provided by mongoose, but I'm not sure if this operation is atomic, that is, if removing the client and an error occurs when removing the rentals, the client is not removed.
ClienteSchema.post('remove', doc => {
AlquilerSchema.deleteMany({cliente: doc._id})
});
A solution for what you are looking for is to make a transaction with Mongoose, in this way you make sure that all the documents are deleted correctly and if an error occurs it will return to the previous state of the transaction.
Regarding the
middlewares
Mongoose ones (pre and post), keep in mind that they are designed to handle possible errors that may occur in the actions you want to perform (save, update, etc.).I detail an example of a transaction so you can understand it:
This function could be added as a method to the schema of the collection
Cliente
and thus call it when it is instantiated, I give you an example of how the method could go in the Schema (I skip the connection step) and how it would be used:It would be used:
I hope that with this explanation you can solve your problem.
For any questions, do not hesitate to ask.
All the best