floatleft
floatleft

Reputation: 6561

Sequelize: Modify output of date timestamp using Getters

I need to convert my signup_at timestamp to a certain format each time it's selected from the database.

I want to use a getter for this, but it doesn't appear to be returning the modified data. It continues to return the same date object stored in the database.

var moment = require("moment");

var Referral = sequelize.define("referral", {
    id: {
      allowNull: false,
      type: DataTypes.CHAR(24),
      unique: true,
      primaryKey: true
    },
    active: {
      allowNull: false,
      type: DataTypes.BOOLEAN,
      defaultValue: true
    },
    name: {
      allowNull: true,
      type: DataTypes.STRING
    },
    method: {
      allowNull: true,
      type: DataTypes.STRING
    },
    signup_at: {
      allowNull: false,
      type: DataTypes.DATE,
      get: function() {
        return moment(this.getDataValue("signup_at")).format("MM/DD/YYYY");
      }
    }
});


Referral.findAll({
 where: {
  active: true
 },
 raw: true
}).then(function(referrals) {
  console.log(referrals);
});

Upvotes: 3

Views: 910

Answers (1)

aristotll
aristotll

Reputation: 9175

Try the following code

Referral.findAll({
    where: {
        active: true
    },
    raw: false
}).then(function (referrals) {
    referrals.forEach(function (referral, index, array) {
        var value = referral.get();
        console.log(value);
    });
});

It seems raw = true won't use the getter function.

You may make raw false and call the get explicitly.

Upvotes: 1

Related Questions