Change Model values after load in Mongoose

前端 未结 1 467
庸人自扰
庸人自扰 2021-01-11 15:55

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.<

相关标签:
1条回答
  • 2021-01-11 16:38

    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 讨论(0)
提交回复
热议问题