保存在数据库中之前先将名称大写-实例挂钩 [英] sequelize capitalize name before saving in database - instance hook
本文介绍了保存在数据库中之前先将名称大写-实例挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是续集的新手,每次创建新的"Rider"时,我都尝试使用大写的名字的第一个字母,以便在我的桌子上大写.我无法做到这一点:
I am new to sequelize and I am trying to capitalize the first letter of the name every time I create a new "Rider" so it looks capitalized on my table. I haven't been able to do it:
这是我的模型:
const db = require("./db");
const Sequelize = require("sequelize");
//(w / WSL ranking, Last tournament won, Country, favorite wave, current board).
const Rider = db.define("rider", {
name: {
type: Sequelize.STRING,
allowNull: false
},
country: Sequelize.STRING,
wsa: {
type: Sequelize.INTEGER,
allowNull: false
},
currentBoard: {
type: Sequelize.STRING,
allowNull: false
},
favWave: Sequelize.STRING,
lastTournamentWon: Sequelize.STRING,
img: {
type: Sequelize.TEXT,
defaultValue:
"no_found.png"
}
});
Rider.beforeCreate = () => {
return this.name[0].toUpperCase() + this.name.slice(1);
}
module.exports = Rider;
当我创建新行时,该名称没有大写,并且我无法找出原因?我是否必须将实例和回调函数作为参数传递给我的钩子?
When I create a new row, the name doesn't capitalize and I haven't been able to spot why? Do I have to pass an instance and a callback function as parameters for my hook?
推荐答案
如@iwaduarte的评论中所述,您需要像下面那样传递实例
As mentioned in the comment by @iwaduarte, you need to pass the instance, like below
const User = sequelize.define('user', {
username: Sequelize.STRING,
});
User.hook('beforeCreate', (user, options) => {
user.username = user.username.charAt(0).toUpperCase() + user.username.slice(1);
});
sequelize.sync({ force: true })
.then(() => User.create({
username: 'one',
}).then((user) => {
console.log(user.username);
})
);
这篇关于保存在数据库中之前先将名称大写-实例挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文