Mongoose trigger on insert data
Im useing nest js framework with mongoose, I need to implement trigger on one of my tables and send notification to users when a record insert ro table please tell me what is the best practice to do this in nest js
Solution 1:
The NestJS mongoose module supports hooks. Check out the docs here.
@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: Cat.name,
useFactory: () => {
const schema = CatsSchema;
schema.pre('save', function() { console.log('Hello from pre save') });
return schema;
},
},
]),
],
})
export class AppModule {}
Solution 2:
Another avenue you may be interested in is something called Change Streams, which are native in MongoDB. Essentially, you "watch" for changes on a collection/document.
https://docs.mongodb.com/drivers/node/current/usage-examples/changeStream/