Inject model into schema for post hook
See original GitHub issueLet’s say we’re having two schemas called conversation
and message
.
MessageSchema
:
export const MessageSchema = new mongoose.Schema({
Created: { type: Date, default: Date.now },
ConversationID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'conversation'
},
SenderID: mongoose.Schema.Types.ObjectId,
Text: String, // Message Text oder Filename
}
ConversationSchema
:
export const ConversationSchema = new mongoose.Schema({
Title: String,
Description: String,
Participants: [{
type: mongoose.Schema.Types.ObjectId // userIDs
}],
Created: {
type: Date,
default: Date.now
}
});
Whenever a conversation is deleted I want mongoose to automatically delete all related messages. Mongoose has a functionality called Middleware
for that (also called pre and post hooks).
Docs: http://mongoosejs.com/docs/middleware.html
The problem is, that I’ll need the MessageModel
instance for the remove query.
ConversationSchema.post('findOneAndRemove', function (err, doc, next) {
// Remove messages related to this conversation
Message.remove({
ConversationID: doc._id
}).then(() => {
next();
});
});
How can I retrieve the model instance? As far as I understand there is no nestjs injection available for schemas.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:4
- Comments:6 (1 by maintainers)
Top Results From Across the Web
pre-hook & post-hook
A SQL statement (or list of SQL statements) to be run before or after a model, seed, or snapshot is built. Pre- and...
Read more >Mongoose v6.8.1: Middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on ......
Read more >Mongoose pre and post hooks do not work on models ...
I am using mongoose 6.1.5. I have a collection containing multiple types of related documents. Here is parameter-descriptor-item.model.js
Read more >@pre & @post | typegoose
@pre is used to set Document & Query pre hooks, works like schema.pre only difference is the switched options and method ( fn...
Read more >Mongoose | Ts.ED - A Node.js and TypeScript Framework ...
Add a plugin, PreHook method and PostHook on your model; Inject a Model to a Service, Controller, Middleware, etc. Create and manage multiple ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I just want to leave a comment here for anyone who comes across this in the future. For my purposes, I was interested in using multiple models in the schema definitions of each other within pre/post hooks, e.g. I want delete all user posts when a user gets deleted, etc. I found that registering hooks with asynchronous behavior wasn’t working with the
.forFeature()
, did some digging in the documentation, triedforFeatureAsync()
, found this issue, and was able to piece together a solution.You can use
.forFeatureAsync()
to provide your models, as outlined in the documentation, and inject the other modules into the factory functions you define in the exact same way you would in a service. The only difference being that you do not decorate any schema factory method parameters with@InjectModel
, but instead add an entry in theinject
array of theforFeatureAsync
where the entry is defined by using thegetModelToken()
method from mongoose.util.ts mentioned in the testing portion of the documentation.Here is a short example:
I created a solution to have Mongoose middleware with keeping OOP principles, but I believe that the functions of decorators could be improved. At least, the final view looks great.