如何在Sequelize create方法返回结果中排除password属性?
解决Sequelize创建用户后返回对象不含password的问题
方法一:通过Sequelize模型/查询配置实现
1. 全局默认排除password(推荐)
在定义User模型时配置defaultScope,让所有默认查询(包括create)自动排除password字段:
const User = sequelize.define('User', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, password: { type: DataTypes.STRING, allowNull: false } }, { defaultScope: { attributes: { exclude: ['password'] } } });
配置后,不管是create、findOne还是其他默认查询,返回的实例都不会包含password属性。
2. 单次查询临时排除
如果只想在本次create操作中排除password,不需要全局配置,可以在调用create时传入attributes参数:
const user = await User.create({ email, password }, { attributes: { exclude: ['password'] } });
方法二:通过JavaScript逻辑手动移除
如果不想修改Sequelize配置,也可以在创建用户后手动移除password属性:
1. 直接修改Sequelize实例的dataValues
const user = await User.create({ email, password }); delete user.dataValues.password;
2. 转换为普通对象后移除
如果需要返回普通JSON对象,先调用toJSON()转换后再删除:
const user = await User.create({ email, password }); const userWithoutPwd = user.toJSON(); delete userWithoutPwd.password;
内容的提问来源于stack exchange,提问作者Mohammad ARZ
相关产品推荐
相关产品推荐

