Answers for "set: function (val) in 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
0

getter and setter sequelize simple way

// method 2
//define 
const User = sequelize.define('user', {
  firstName: DataTypes.TEXT,
  lastName: DataTypes.TEXT,
  fullName: {
    type: DataTypes.VIRTUAL,
    get() {
      return `${this.firstName} ${this.lastName}`;
    },
    set(value) {
      throw new Error('Do not try to set the `fullName` value!');
    }
  }
});

//usage 
const user = await User.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName); // 'John Doe'
Posted by: Guest on December-24-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language