最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change Model values after load in Mongoose - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Feb 4, 2013 at 18:54 LanboLanbo 15.7k16 gold badges74 silver badges147 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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();
});
发布评论

评论列表(0)

  1. 暂无评论