12

In my mongoose model, I have some stats that are dependent on time. My idea is to add a middleware to change these stats right after the model has been loaded.

Unfortunately, the documentation on the post-Hooks is a bit lacking in clarity. It seems like I can use a hook like this:

schema.post('init', function(doc) {
    doc.foo = 'bar';
    return doc;
});

Their only examples involve console.log-outputs. It does not explain in any way if the doc has to be returned or if a change in the post-Hook is impossible at all (since it is not asynchronous, there might be little use for complex ideas).

If the pre on 'init' is not the right way to automatically update a model on load, then what is?

Lanbo
  • 15,118
  • 16
  • 70
  • 147

1 Answers1

21

This is how we update models on load, working asynchronously:

schema.pre('init', function(next, data) {
  data.property = data.property || 'someDefault';
  next();
});

Pre-init is special, the other hooks have a slightly different signature, for example pre-save:

schema.pre('save', function(next) {
  this.accessed_ts = Date.now();
  next();
});
hunterloftis
  • 13,386
  • 5
  • 48
  • 50
  • 2
    So pre-init is actually after the data is loaded? And the document is not in the `this` context? – Lanbo Feb 04 '13 at 21:03
  • 4
    Pre-init is after the data is loaded, but *before* the document is hydrated with that data (afaik). Since the data has not been placed in the document yet, the "this" context exists (it's still the doc) but it will be empty (iirc). – hunterloftis Feb 04 '13 at 22:25