I wrote a BeforeCreate hook in my sequelize mannequin. when i hit create consumer route then it saying consumer.user_id cannot be null and even earlier than create hook operate not executing. I’ve adopted documentation of sequelize.They’ve talked about similar as I exploit.I wrote a BeforeCreate hook in my sequelize mannequin. when i hit create consumer route then it saying consumer.user_id cannot be null and even earlier than create hook operate not executing. I’ve adopted documentation of sequelize.They’ve talked about similar as I exploit.
const sequelize = require("kvell-db-plugin-sequelize").dbInstance;
const Sequelize = require("kvell-db-plugin-sequelize").dbLib;
const shortid = require("shortid");
const Person = sequelize.outline(
"consumer",
{
id: {
sort: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false
},
user_id: {
sort: Sequelize.STRING,
allowNull: false,
primaryKey: true,
distinctive: true
},
user_fname: {
sort: Sequelize.STRING,
allowNull: false
},
user_lname: {
sort: Sequelize.STRING,
allowNull: false
},
user_fullName: {
sort: Sequelize.VIRTUAL,
get() {
return `${this.user_fname} ${this.user_lname}`;
},
set(worth) {
throw new Error("Don't attempt to set the `fullName` worth!");
}
},
user_email: {
sort: Sequelize.STRING,
allowNull: false,
primaryKey: true,
validate: {
isEmail: true
},
distinctive: {
args: true,
msg: "Electronic mail tackle already in use!"
}
},
user_credential: {
sort: Sequelize.STRING,
allowNull: false
},
user_roles: {
sort: Sequelize.ARRAY(Sequelize.STRING),
allowNull: false,
defaultValue: ["Admin"]
},
admin: {
sort: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: true
},
user_img: {
sort: Sequelize.STRING,
allowNull: true
}
},
{
timestamps: true
}
);
Person.beforeCreate(async (consumer, choices) => {
console.log("inside hooks");
let id = `user_${shortid.generate()}`;
consumer.user_id = id;
});
const toJSON = Person.prototype.toJSON;
Person.prototype.toJSON = operate({ attributes = [] } = {}) {
const obj = toJSON.name(this);
if (!attributes.size) {
return obj;
}
return attributes.scale back((consequence, attribute) => {
consequence[attribute] = obj[attribute];
return consequence;
}, {});
};
module.exports = Person;