![](/img/trans.png)
[英]how to return a newly created object when using sequelize transcation?
[英]How to return only specific attributes when using Sequelize Create method
我一直在搜索 Sequelize 文檔和論壇以尋找正確的語法,看來我的做法是正確的,但由於某種原因,密碼字段仍在響應有效負載中返回...
以下鏈接顯示了我在 Sequelize 3.11 版中添加的屬性排除語法: https : //github.com/sequelize/sequelize/issues/4074
有誰知道我在這里可能會錯過什么? 下面是來自Insert
語句的Create
方法和控制台日志。
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)
};
}
控制台日志
執行(默認):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 ) 返回 *;
用戶:用戶{ dataValues:{ id:6,名字:'James',姓氏:'Martineau',電子郵件:'test@gmail.com',密碼:'$2b$10$7ANyHzs74OXYfXHuhalQ3ewaS4DDem1cHMprKaIa7gO434rlVLKp20',updated :18:15.856Z, createdAt: 2019-02-28T15:18:15.856Z }...
我在文檔中看到,創建模型時不能排除屬性。 僅在您找到模型時排除。
我建議:
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);
};
}
處理此問題的正確方法是利用 Sequelize 公開的實際數據模型上的 afterCreate 和 afterUpdate 掛鈎。 這些鈎子在記錄持久化后被觸發,因此對 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;
},
}
}
);
這是文檔的鏈接: https : //sequelize.org/master/manual/hooks.html
嘗試使用您想要的功能重載 Sequelize Model 類。 例如,在應用程序引導期間運行一次以下代碼:
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;
}, {});
};
之后,您可以像往常一樣使用您的代碼,但帶有一個attributes
選項:
User.toJSON({attributes: ['name', 'etc...']})
。
通過快速閱讀文檔,似乎attributes
僅在查詢中提及,例如:
Model.findAll({
attributes: { exclude: ['baz'] }
});
( http://docs.sequelizejs.com/manual/tutorial/querying.html#attributes )
如果您想使用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 )
User.create(req.body).then(user => { delete user.dataValues.password res.json(user) }).catch(error => { // do something with error })
我知道這是一個老問題,但這是我最近面臨的一個問題。 我解決這個問題的方法是這樣的:
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)
};
您可以像這樣實例化您想要的字段,至少這是我在代碼中隨處可見的
希望這對你也有用:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.