How to apply mongoose middleware

Hi Forest Admin team,

I’m using “forest-express-mongoose”: “^7.0.0” and my models is as :

 module.exports = (mongoose, Mongoose) => {
	const schema = Mongoose.Schema({name : String})
 return mongoose.model('formations', schema);
 }

How I can apply middleware schema.pre and schema.post ?

I tried to do :

 module.exports = (mongoose, Mongoose) => {
	const schema = Mongoose.Schema({name : String});

       schema.pre('save', function (next) {
		console.log('Pre mongoose');
		this.current_score = 999;
		next();
	});

	schema.post('save', function (doc, next) {
		console.log('POST mongoose');
		next();
	});


 return mongoose.model('formations', schema);
 }

but didn’t work.

Expected behavior

Actual behavior

Failure Logs

No failure logs

Context

Please provide any relevant information about your setup.

forest-express-mongoose": “^7.0.0”

Hello @NathanLe,

I think this part of the documentation could help you.

Can you try with the async/await pattern, and tell me if it works?

Let me know :slight_smile:

Thanks for helping me out. That works but not in all cases as I tried. I go with solution catching create and update actions in default routes.

Thanks again!

1 Like