Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose pre findOneAndUpdate hook issues

Tags:

mongoose

I'm trying to update counts on a pre hook. The issue is that for some unknown reason the findOneAndUpdate hook doesn't have access to the document, as far as I can tell.

I would like to do this:

source.pre('findOneAndUpdate', function (next) {
  console.log('------------->>>>>> findOneAndUpdate: ');
  this.objects = this.objects || [];
  this.people = this.people || [];
  this.events = this.events || [];

  this.objectCount = this.objects.length;
  this.peopleCount = this.people.length;
  this.eventCount = this.events.length;

  next();
});

But for some reason the this in the hook isn't the document, its a Query object which seems about useless.

What am I missing? How do I use a pre hook to update counts on a findOneAndUpdate?

like image 214
Justin808 Avatar asked Aug 05 '15 05:08

Justin808


People also ask

What is pre hook in mongoose?

On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.

Why we use pre hook in mongoose?

According to the official mongoose documentation here – Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.

What is pre function in mongoose?

Pre middleware functions are executed one after another, when each middleware calls next . const schema = new Schema(..); schema. pre('save', function(next) { // do stuff next(); }); In mongoose 5. x, instead of calling next() manually, you can use a function that returns a promise.

What is middleware in mongoose?

Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.


1 Answers

You can do smthng like that ->

source.pre('findOneAndUpdate', function (next) {
    console.log('------------->>>>>> findOneAndUpdate: ');
    this._update.$set.objects = [];
    this._update.$set.people = [];
    this._update.$set.events =  [];
    next();
});

pay attention to _update.$set because in the context "this" will be a query. So you can easily add anything you want!

like image 168
user3419036 Avatar answered Sep 18 '22 22:09

user3419036



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!