0

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:

this is my model:

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?

Monique
  • 279
  • 3
  • 20
  • 2
    you have to pass the model in the beforeCreate function and you have to return a promise because it is an async function. this could help: https://stackoverflow.com/questions/31427566/sequelize-create-model-with-beforecreate-hook – iwaduarte Jun 08 '18 at 16:39

1 Answers1

0

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);
  })
);
AbhinavD
  • 6,892
  • 5
  • 30
  • 40
  • Nice! I ended up just assigning an 'afterValidate' hook inside the model itself since I was having trouble with promises while doing the way you just suggested. I will try this out! Thanks a lot! – Monique Jun 12 '18 at 14:26