Mongoose 是否在 pre('save') 中提供对先前属性值的访问? [英] Does Mongoose provide access to previous value of property in pre('save')?

查看:8
本文介绍了Mongoose 是否在 pre('save') 中提供对先前属性值的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 pre('save') 中间件中比较一个属性的新/传入值与该属性的先前值(当前保存在数据库中的值).

I'd like to compare the new/incoming value of a property with the previous value of that property (what is currently saved in the db) within a pre('save') middleware.

Mongoose 是否提供了执行此操作的工具?

Does Mongoose provide a facility for doing this?

推荐答案

Mongoose 允许您配置在其中进行比较的自定义设置器.pre('save') 本身不会给你你需要的东西,而是一起:

Mongoose allows you to configure custom setters in which you do the comparison. pre('save') by itself won't give you what you need, but together:

schema.path('name').set(function (newVal) {
  var originalVal = this.name;
  if (someThing) {
    this._customState = true;
  }
});
schema.pre('save', function (next) {
  if (this._customState) {
    ...
  }
  next();
})

这篇关于Mongoose 是否在 pre('save') 中提供对先前属性值的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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