Answers for "setter getter model javascript sequelize"

2

getter and setter sequelize simple way

method 1:
// step 1 
// define getter and setter in model
const Pug = db.define('pugs', {
  name: {
    type: Sequelize.STRING,
    get () { // this defines the 'getter'
      return this.getDataValue('name') + ' the pug'
    },
    set (valueToBeSet) { // defines the 'setter'
      // use `this.setDataValue` to actually set the value
      this.setDataValue('name', valueToBeSet.toUpperCase())
      // this setter will automatically set the 'name' property to be uppercased
    }
  }
})

//step 2
// use in code controller

// building or creating an instance will trigger the 'set' operation, causing the name to be capitalized
const createdPug = await Pug.create({name: 'cody'})

// when we 'get' createdPug.name, we get the capitalized 'CODY' + ' the pug' from our getter
console.log(createdPug.name) // CODY the pug

// this is the 'set' operation, which will capitalize the name we set
createdPug.name = 'murphy'
console.log(createdPug.name) // MURPHY the pug
Posted by: Guest on December-24-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language