Mongoose: Schema.pre(Array, fn), like `Schema.pre(['save', 'validate'])`

Created on 15 May 2019  路  3Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?
feature

What is the current behavior?
If I want to use middleware in a model I need to define specific operation like 'save', 'findOneAndUpdate', 'update'.

What is the expected behavior?
I hope there can exist a middleware called 'saveOrUpdate', which means whatever create a new document or update an existing document will trigger this middleware.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Node.js 12.0
Mongoose 5.5.8
MongoDB 4.0.9

enhancement

Most helpful comment

You can pass a regular expression to schema.pre() and schema.post(). For example, schema.pre(/^(save|update)$/, fn). See Schema#pre() API docs

All 3 comments

You can pass a regular expression to schema.pre() and schema.post(). For example, schema.pre(/^(save|update)$/, fn). See Schema#pre() API docs

You can pass a regular expression to schema.pre() and schema.post(). For example, schema.pre(/^(save|update)$/, fn). See Schema#pre() API docs

It is cool, thanks. I will read document more carefully next time.
@vkarpov15 Can I know the reason to support regex rather than array or blank separated string here because my intuition is passing an array like ['save', 'findOneAndUpdate'] or string like 'save findOneAndUpdate', which have been widespread used in other parameters in mongoose.

@Mangosteen-Yang we'll add support for that

Was this page helpful?
0 / 5 - 0 ratings