简体   繁体   中英

Sequelize.js setter function not working as I expect

I'm having trouble using the setter functions on my Sequelize js model properties.

What I want to do is when one property is given a value use that value to populate another property in the table at the same time.

In my model this is the code I have for the property in question...

date_time_paid: {
  type:DataTypes.DATE,
  set(val) {
    const date = new Date(val);
    this.setDataValue('date_time_paid', val);  // set the the current property
    this.setDataValue('month_paid', `${date.getFullYear()}-${(date.getMonth() + 1)}`);  //also set another property on the same row
  },
},

What I expect to happen is for the date_time_paid column to store the raw value and the month_paid column to store a string derived from it. But when I run my seeder to populate the table with test data the value for the month_paid column remains null.

  1. Is this the correct use of a setter function?
  2. If it is what have I done wrong that means it's not working?

I think you need a just a getter. Forget about date_time_paid and make getter for month_paid :

get month_paid(){
    const date = new Date(this.date_time_paid);
    return `${date.getFullYear()}-${(date.getMonth() + 1)}`;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM