本文介绍了Sequelize:不返回密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Sequelize 为用户记录执行数据库查找,并且我希望模型的默认行为返回该记录的 password 字段.password 字段是一个哈希值,但我仍然不想返回它.

I'm using Sequelize to do a DB find for a user record, and I want the default behavior of the model to not return the password field for that record. The password field is a hash but I still don't want to return it.

我有几个可行的选择,但似乎没有一个特别好:

I have several options that will work, but none seems particularly good:

  1. User 模型创建一个自定义类方法 findWithoutPassword,并在该方法中使用 User.find>attributes 设置如 Sequelize 文档

  1. Create a custom class method findWithoutPassword for the User model and within that method do a User.find with the attributes set as shown in the Sequelize docs

做一个普通的User.find并在控制器中过滤结果(非首选)

Do a normal User.find and filter the results in the controller (not preferred)

使用其他库去除不需要的属性

Use some other library to strip off unwanted attributes

有没有更好的办法?最重要的是,如果有一种方法可以在 Sequelize 模型定义中指定从不返回 password 字段,但我还没有找到这样做的方法.

Is there a better way? Best of all would be if there is a way to specify in the Sequelize model definition to never return the password field, but I haven't found a way to do that.

推荐答案

我建议重写 toJSON 函数:

sequelize.define('user', attributes, {
  instanceMethods: {
    toJSON: function () {
      var values = Object.assign({}, this.get());

      delete values.password;
      return values;
    }
  }
});

或者在 sequelize v4

Or in sequelize v4

const User = sequelize.define('user', attributes, {});

User.prototype.toJSON =  function () {
  var values = Object.assign({}, this.get());

  delete values.password;
  return values;
}

toJSON 在数据返回给用户时被调用,因此最终用户不会看到密码字段,但它仍然可以在您的代码中使用.

toJSON is called when the data is returned to the user, so end users won't see the password field, but it will still be available in your code.

Object.assign 克隆返回的对象 - 否则您将从实例中完全删除该属性.

Object.assign clones the returned object - Otherwise you will completely delete the property from the instance.

这篇关于Sequelize:不返回密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:59