在保存到数据库之前将名称大写

编程入门 行业动态 更新时间:2024-10-28 03:18:28
本文介绍了在保存到数据库之前将名称大写 - 实例挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是 sequelize 的新手,每次创建新的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); }) );

更多推荐

在保存到数据库之前将名称大写

本文发布于:2023-10-13 14:35:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前将   名称   数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!