最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sequelize get virtual field - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Feb 12, 2015 at 16:36 TinoTino 3,3686 gold badges48 silver badges79 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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);
 }
}

Ok I solved it:

var md5 = require('MD5');

getterMethods: {
        hash: function () {
          var string =  this.id+''+this.randomfieldone +''+this.randomfieldtwo;
          var hash = md5(string);
          return hash;
        }
    }

if you set getter function for a property in schema, the property will be included when the instance is converted to object or json.

发布评论

评论列表(0)

  1. 暂无评论