[英]How to return only specific attributes when using Sequelize Create method
I have been searching through Sequelize documentation and forums for the correct syntax and it seems I am doing it the right way, but for some reason the password field is still being returned in the response payload...我一直在搜索 Sequelize 文档和论坛以寻找正确的语法,看来我的做法是正确的,但由于某种原因,密码字段仍在响应有效负载中返回...
The following link shows the attributes exclude syntax I am using was added in version 3.11 of Sequelize: https://github.com/sequelize/sequelize/issues/4074以下链接显示了我在 Sequelize 3.11 版中添加的属性排除语法: https : //github.com/sequelize/sequelize/issues/4074
Anyone know what I might be missing here?有谁知道我在这里可能会错过什么? Below is the
Create
method and the console log from the Insert
statement.下面是来自
Insert
语句的Create
方法和控制台日志。
Create
method Create
方法
async create(req, res) {
try {
let user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
}, {
attributes: {
exclude: ['password']
}
});
console.log("USER: ", user);
res.status(201).send(user.toJSON());
}
catch (error) {
res.status(500).send(error)
};
} }
Console Log控制台日志
Executing (default): INSERT INTO "Users" ("id","firstName","lastName","email","password","createdAt","updatedAt") VALUES (DEFAULT,'James','Martineau','test@gmail.com','$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2','2019-02-28 15:18:15.856 +00:00','2019-02-28 15:18:15.856 +00:00') RETURNING *;
执行(默认):INSERT INTO "Users" ("id","firstName","lastName","email","password","createdAt","updatedAt") VALUES (DEFAULT,'James','Martineau' ,'test@gmail.com','$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2','2019-02-28 15:18:15.856 +00:00','2019:05:2018 ) 返回 *;
USER: User { dataValues: { id: 6, firstName: 'James', lastName: 'Martineau', email: 'test@gmail.com', password: '$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp2', updatedAt: 2019-02-28T15:18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...
用户:用户{ dataValues:{ id:6,名字:'James',姓氏:'Martineau',电子邮件:'test@gmail.com',密码:'$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp20',updated :18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...
I see in the document , you can't exclude attributes when you create a model.我在文档中看到,创建模型时不能排除属性。 Only exclude when you find a model.
仅在您找到模型时排除。
I suggest:我建议:
async create(req, res);
{
try {
let user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
delete user["password"];//delete field password
console.log("USER: ", user);
res.status(201).send(user.toJSON());
}
catch (error) {
res.status(500).send(error);
};
}
The proper way to handle this is to leverage the afterCreate and afterUpdate hooks on the actual data model, that Sequelize exposes.处理此问题的正确方法是利用 Sequelize 公开的实际数据模型上的 afterCreate 和 afterUpdate 挂钩。 These hooks are fired after the record is persisted, so any mutations to the dataValues will only be reflected in the return.
这些钩子在记录持久化后被触发,因此对 dataValues 的任何更改都只会反映在返回值中。
sequelize.define(
'User',
{
id: { type: DataType.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true },
username: { type: DataType.STRING, allowNull: false },
password: { type: DataType.STRING, allowNull: false }
},
{
hooks: {
afterCreate: (record) => {
delete record.dataValues.password;
},
afterUpdate: (record) => {
delete record.dataValues.password;
},
}
}
);
Here is a link to the documentation: https://sequelize.org/master/manual/hooks.html这是文档的链接: https : //sequelize.org/master/manual/hooks.html
Try overloading Sequelize Model class with your desired functionality.尝试使用您想要的功能重载 Sequelize Model 类。 For example, run following code once during application bootstrap:
例如,在应用程序引导期间运行一次以下代码:
import {Model} from 'sequelize';
const toJSON = Model.prototype.toJSON;
Model.prototype.toJSON = function ({attributes = []} = {}) {
const obj = toJSON.call(this);
if (!attributes.length) {
return obj;
}
return attributes.reduce((result, attribute) => {
result[attribute] = obj[attribute];
return result;
}, {});
};
After that, you can use your code as usual, but with an attributes
option:之后,您可以像往常一样使用您的代码,但带有一个
attributes
选项:
User.toJSON({attributes: ['name', 'etc...']})
. User.toJSON({attributes: ['name', 'etc...']})
。
With a quick read through the docs, it seems attributes
is only mentioned within queries like:通过快速阅读文档,似乎
attributes
仅在查询中提及,例如:
Model.findAll({
attributes: { exclude: ['baz'] }
});
( http://docs.sequelizejs.com/manual/tutorial/querying.html#attributes ) ( http://docs.sequelizejs.com/manual/tutorial/querying.html#attributes )
If you want to exclude password
with create
, you could do something like:如果您想使用
create
排除password
,您可以执行以下操作:
let user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
}, {
fields: ['firstName', 'lastName', 'email']
});
( http://docs.sequelizejs.com/manual/tutorial/instances.html#creating-persistent-instances ) ( http://docs.sequelizejs.com/manual/tutorial/instances.html#creating-persistent-instances )
User.create(req.body).then(user => { delete user.dataValues.password res.json(user) }).catch(error => { // do something with error })
I know it's an old question, but it's a problem i faced recently.我知道这是一个老问题,但这是我最近面临的一个问题。 The way I solved this, is like this:
我解决这个问题的方法是这样的:
try {
const { firstName, lastName, email } = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
})
const user = { firstName, lastName, email }
}
console.log("USER: ", user);
res.status(201).send(user.toJSON());
}
catch (error) {
res.status(500).send(error)
};
You can instantiate the fields you want like this, at least it's what i'm doing everywhere in my code您可以像这样实例化您想要的字段,至少这是我在代码中随处可见的
hope this works for you too :)希望这对你也有用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.