问题描述
我正在使用 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:
为
User
模型创建一个自定义类方法findWithoutPassword
,并在该方法中使用User.find
>attributes 设置如 Sequelize 文档
Create a custom class method
findWithoutPassword
for theUser
model and within that method do aUser.find
with theattributes
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:不返回密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!