猫鼬在预保存钩子中获取db值 [英] mongoose get db value in pre-save hook

查看:71
本文介绍了猫鼬在预保存钩子中获取db值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道像这样的预保存猫鼬钩子中脏道具的干净"值是什么:

I want to know what the 'clean' value of a dirty prop is in a pre-save mongoose hook like this:

UserSchema.pre('save', function(next) {
    var user = this;

    if (user.isModified('password')){
       //i want to know what the value of user.password was before it was changed
    }
    next()
}

是否可以在数据库中查找旧值而不查找它?

Is it possible to look up the old value without looking it up in the db?

推荐答案

默认情况下,不存储旧值.您需要做的是使用post init钩子(猫鼬功能)跟踪旧数据.

By default, the old values are not stored. You would have to do is track the old data with a post init hook (a mongoose feature).

我们要做的是将原始文档的副本附加到从MongoDB中提取的所有项目.对于需要获取脏数据进行比较的每个模式,我们都有以下代码:

What we do is attach copy of the original document to all items pulled from MongoDB. We have this code for each schema we need to get pre-dirty data for comparison:

schema.post( 'init', function() {
    this._original = this.toObject();
} );

NodeJS非常有效,并且在可能的情况下会在写入时进行复制,因此除非修改整个文档,否则不会看到两倍的内存消耗.只有这样_original才会真正消耗双倍的内存.

NodeJS is pretty efficient, and does copy on write when possible, so you don't see double the memory consumption unless you modify the entire document. Only then does _original actually consume double the memory.

这篇关于猫鼬在预保存钩子中获取db值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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