2017-05-21 42 views
0

我對我的用戶喜歡這樣的模型定義getter方法,getter方法不工作的PostgreSQL模型

'use strict'; 
module.exports = function(sequelize, DataTypes) { 
    var Users = sequelize.define('Users', { 
    name: DataTypes.STRING, 
    uuid: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true 
    }, 
    poll_ids: DataTypes.ARRAY(DataTypes.INTEGER) 
    }, { 
    classMethods: { 
     associate: function(models) { 
     // associations can be defined here 
     Users.hasMany(models.Polls, { 
      foreignKey: 'userId' 
     }); 
     } 
    }, 
    getterMethods: { 
     getUUID() { 
     return this.getDataValue('uuid'); 
     } 
    } 
    }); 
    return Users; 
}; 

而且我試圖像這樣運行它,

models.Users.create({ 
     name: name, 
     uuid: uuid, 
     poll_ids: poll_ids 
    }).then((user) => { 
     console.log(user.getUUID()); 
    }); 

然而,我當我這樣做時得到以下錯誤。

Unhandled rejection TypeError: user.getUUID is not a function

注意:我已經用sequelize-cli定義了我的模型和遷移。在完成遷移之後,我將getterMethods添加到模型文件中。我運行了一個撤消遷移,同步數據庫並再次遷移,以確保遷移文件反映了我的模型的變化。但是,我不確定是否需要對遷移文件進行更新。我哪裏錯了?

回答

0

好的,終於有事可做了。將其定義爲模型的一部分不起作用,但出於某種原因將其定義爲屬性工程的一部分。

module.exports = function(sequelize, DataTypes) { 
    var Users = sequelize.define('Users', { 
    name: DataTypes.STRING, 
    uuid: { 
     type: DataTypes.INTEGER, 
     allowNull: false, 
     primaryKey: true, 
     get() { 
     return this.getDataValue('uuid'); 
     } 
    }, 
    poll_ids: DataTypes.ARRAY(DataTypes.INTEGER) 
    }, { 
    classMethods: { 
     associate: function(models) { 
     // associations can be defined here 
     Users.hasMany(models.Polls, { 
      foreignKey: 'userId' 
     }); 
     } 
    } 
    }); 
    return Users; 
}; 

在routes文件

models.Users.create({ 
     name: name, 
     uuid: uuid, 
     poll_ids: poll_ids 
    }).then((user) => { 
     console.log('Finally'); 
     console.log(user.get('uuid')); 
    }); 
0

我沒有在文檔一段時間看到它,但定義instanceMethods好像你正在尋找實現與getUUID()

什麼工作

getterMethods:替換爲instanceMethods,並且您應該能夠在Users型號的實例上訪問.getUUID(