在Mongoose中加载后更改模型值 [英] Change Model values after load in Mongoose

查看:88
本文介绍了在Mongoose中加载后更改模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的猫鼬模型中,我有一些依赖于时间的 stats 。我的想法是在模型加载后立即添加中间件来更改这些统计信息。

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.

不幸的是,关于帖子 -Hooks的文档有点缺乏清晰度。好像我可以使用这样的钩子:

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;
});

他们唯一的例子涉及 console.log - 输出。它不以任何方式解释是否必须返回 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).

如果上的'init'不是在加载时自动更新模型的正确方法,那是什么?

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

推荐答案

这是怎么回事我们在加载时更新模型,异步工作:

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

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

pre-init很特别,其他挂钩的签名略有不同,例如pre-save:

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();
});

这篇关于在Mongoose中加载后更改模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆