Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notes on Hooks, Middleware in Mongoose #13

Open
natac13 opened this issue Mar 10, 2016 · 0 comments
Open

Notes on Hooks, Middleware in Mongoose #13

natac13 opened this issue Mar 10, 2016 · 0 comments

Comments

@natac13
Copy link

natac13 commented Mar 10, 2016

Pre Hooks

  • can have serial or parallel hooks
// user is an instance of Model, which are mongoose documents that have a one-to-one mapping to a record in the database
const user = new SchemaModel( ... );

// serial hooks
user.pre('save', function(next) {
  // do stuff
  next();
});

// parallel hooks
user.pre('save', true, function(next, done) {
  // do synchronous stuff
  // then pass control to next middleware/DB
  next();

  // do **a**synchronous stuff
 setTimeout(done, 100000);
});

Use Case

  • removing a user from the database will remove all his post.
  • deleting contact could block them as well...
    If there is an error that I want to propagate then pass in a new Error() to the next() function.
    Then when the user doc calls save() then the error will show up in the callback/promise
user.save()
  .then(function fulfilled() {... })
  .catch(function handleError(error) { 
  // this is where Ill find the error passed to next()
  console.log(error); 
} 

Post Hooks

  • no flow control (done())
  • can still happen in a serial fashion, by giving next() as second parameter
  • a save() call triggers the 'validate' hook. Note this cause all pre & post 'validate' hooks to happen before any saving to the database occurs.
user.post('save', function(doc) {
  // Do stuff after save
}

// can chain them 
user.post('save', function(doc, next) {
  // do stuff then pass to next post hook
  next();
}

Important

  • hooks and not triggered with update() and findOneAndUpdate()
  • Mongoose 4.0 has specific hooks for these
user.pre('update', function() {...});
user.pre('find', function() {...});
@natac13 natac13 changed the title Note on Hooks, Middleware in Mongoose Notes on Hooks, Middleware in Mongoose Mar 10, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant