Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize get virtual field

for sync reasons I would like to create a hash of certain fields of a row as a virtual field.

My sequelize model looks like this:

var crypto = require('crypto');

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('transactions', { 
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    randomfieldone: {
      type: DataTypes.BIGINT,
      allowNull: true,
    },
    randomfieldtwo: {
      type: 'NUMERIC',
      allowNull: false,
    },
    hash: {
      type: DataTypes.VIRTUAL,
      set: function (val) {
        var string = this.randomfieldone+''+this.randomfieldtwo;
        var hash = crypto.createHash('md5');
        hash.update(string);
        hash.digest('hex');
        this.setDataValue('hash', hash);
     }
    }
  },{
    timestamps: false
  });
};

When I try to output that, I get 'undefined'.

I would like to be able to access it like any other 'real' field.

console.log(row.hash)  

What am I doing wrong here?

like image 310
Tino Avatar asked Sep 14 '25 02:09

Tino


1 Answers

I am use

hash: {
  type: DataTypes.VIRTUAL,
  set: function (val) {
    var string = this.get("randomfieldone")+''+this.get("randomfieldtwo");
    var hash = crypto.createHash('md5');
    hash.update(string);
    hash.digest('hex');
    this.setDataValue('hash', hash);
 }
}
like image 57
Ronald Coarite Avatar answered Sep 16 '25 15:09

Ronald Coarite