gpt4 book ai didi

node.js - sequelize beforeCreate Hook 未执行

转载 作者:行者123 更新时间:2023-12-03 22:22:37 24 4
gpt4 key购买 nike

我在我的 sequelize 模型中写了一个 BeforeCreate 钩子(Hook)。当我点击创建用户路由时,它说 user.user_id 不能为空,甚至在创建钩子(Hook)函数未执行之前。我遵循了 sequelize 的文档。他们提到的和我使用的一样。我在我的 sequelize 模型中编写了一个 BeforeCreate 钩子(Hook)。当我点击创建用户路由时,它说 user.user_id 不能为空,甚至在创建钩子(Hook)函数未执行之前。我遵循了 sequelize 的文档。他们提到的和我使用的一样。

const sequelize = require("kvell-db-plugin-sequelize").dbInstance;
const Sequelize = require("kvell-db-plugin-sequelize").dbLib;
const shortid = require("shortid");
const User = sequelize.define(
"user",
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false
},
user_id: {
type: Sequelize.STRING,
allowNull: false,
primaryKey: true,
unique: true
},
user_fname: {
type: Sequelize.STRING,
allowNull: false
},
user_lname: {
type: Sequelize.STRING,
allowNull: false
},
user_fullName: {
type: Sequelize.VIRTUAL,
get() {
return `${this.user_fname} ${this.user_lname}`;
},
set(value) {
throw new Error("Do not try to set the `fullName` value!");
}
},
user_email: {
type: Sequelize.STRING,
allowNull: false,
primaryKey: true,
validate: {
isEmail: true
},

unique: {
args: true,
msg: "Email address already in use!"
}
},
user_credential: {
type: Sequelize.STRING,
allowNull: false
},
user_roles: {
type: Sequelize.ARRAY(Sequelize.STRING),
allowNull: false,
defaultValue: ["Admin"]
},
admin: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: true
},
user_img: {
type: Sequelize.STRING,
allowNull: true
}
},
{
timestamps: true

}
);

User.beforeCreate(async (user, options) => {
console.log("inside hooks");
let id = `user_${shortid.generate()}`;
user.user_id = id;
});

const toJSON = User.prototype.toJSON;

User.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;
}, {});
};

module.exports = User;

最佳答案

真正的答案(在其中一条评论中提到但未明确说明)是 beforeCreate模型验证后应用 Hook 。
这意味着如果您的模型中有任何字段(例如 id )不能为空,Sequelize 将在应用 beforeCreate 之前对其进行评估。 field 。在您的情况下,Sequelize 永远不会达到 beforeCreate钩子(Hook),因为 null id每次都验证失败。
您接受的答案通过设置 allowNull = true 来解决这个问题,从而绕过验证您的(短暂)null id .但是更好的选择(而不是通过允许 null id 来扭曲您的模型)几乎肯定是使用正确的钩子(Hook):beforeValidate .在评估模型标准之前应用此 Hook 。
这是一个非常简单的改变:

User.beforeValidate(async (user, options) => {
console.log("inside hooks");
let id = `user_${shortid.generate()}`;
user.user_id = id;
});
注意: async这里是多余的。

关于node.js - sequelize beforeCreate Hook 未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com