Monday 30 November 2020

Mongoose Pre and Post hook: stopping a query from execution

I am working on versioning changes for an application. I am making use of the mongoose pre-hook to alter the queries before processing according to the versioning requirements, I came across a situation where I need to do a separate query to check whether the other document exists and if it is I don't have to execute the current query as shown below,

schema.pre('find', { document: false, query: true }, async function (next) {
  const query = this.getQuery();
  const doc = await model.find(query).exec();
  if (!doc) {
    const liveVersion = { ...query, version: "default" };
    this.setQuery(liveVersion);
  } else {
    return doc;
  }
});

In the above find pre-hook, I am trying to

  • check the required doc exists in the DB using the find query and return if does exist and
  • if the document does not exist, I am executing the query by setting the default version based query.

The problem here is mongoose will execute the set query no matter what and the result its returning is also the one which I got for the this.setQuery, not the other DB query result(doc).

Is there a way to stop the default query execution in mongoose pre-hook?

Any help will be appreciated.



from Mongoose Pre and Post hook: stopping a query from execution

No comments:

Post a Comment