sequelize模型自定义方法返回undefined

时间:2016-04-26 13:11:19

标签: javascript methods model undefined sequelize.js

在我的应用程序上我有用户和一些用户是医务人员,一些是牙医,一些是营养师,当我得到我的用途我想用用户和用户数据发回json,这个数据基于两列用户(model_id和model),我尝试使用名为 morphTo 的自定义方法进行操作,所以我有一个名为users的模型

module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('users', {
  email: {type: Sequelize.STRING, field: 'email'},
  password: Sequelize.STRING,
  name: Sequelize.STRING,
  company_id: Sequelize.INTEGER,
  rg: Sequelize.STRING,
  cpf: Sequelize.STRING,
  birth_date: Sequelize.STRING,
  sex: Sequelize.STRING,
  address: Sequelize.STRING,
  number: Sequelize.STRING,
  complement: Sequelize.STRING,
  neighborhood: Sequelize.STRING,
  city: Sequelize.STRING,
  cep: Sequelize.STRING,
  uf: Sequelize.STRING,
  obs: Sequelize.STRING,
  status_id: Sequelize.INTEGER,
  model_id: Sequelize.INTEGER,
  model: Sequelize.STRING,
  deleted_at: Sequelize.STRING,
  created_at: Sequelize.STRING,
  updated_at: Sequelize.STRING,
  }, {timestamps:false, attributes: { exclude : [ 'password' ]},
      classMethods: {
        associate: function(models) {
          user.belongsToMany(models.groups, {
          through: {
          model: models.user_groups
          }, foreignKey:'user_id', as: 'groups'}),
          user.belongsToMany(models.permissions, {
          through: {
          model: models.user_permissions
          }, foreignKey:'user_id', as: 'permissions'})
        },
        morphTo: function(models, model_id, model){ 
          if(model == 'medics'){
            models.medics.findById(model_id).then(function(results) {

              return results;

            });

          }else if(model == 'employees'){
            models.employees.findById(model_id).then(function(results) {

              return results;

            });
          }
        }
      }});

  return user;

}

在我的资源上我有这个

models.users.findById(req.params.id).then(function(results) {
        if(results)
            console.log(models.users.morphTo(models, results.dataValues.model_id, results.dataValues.model));
        else
            res.status(204).send();
    });

我的控制台正在运行查询,但返回是“未定义”

Executing (default): SELECT `id`, `crm` FROM `medics` AS `medics` WHERE `medics`.`id` = 1

我忘记了什么?

1 个答案:

答案 0 :(得分:0)

我认为你的承诺存在问题:

console.log(models.users.morphTo(models, results.dataValues.model_id, results.dataValues.model));

这是一个异步调用。你不应该立刻期待答案,你应该期待一个承诺。

试试这个:

models.users.findById(req.params.id).then(function(results) {
    if(results) {
        models.users.morphTo(models, results.dataValues.model_id, results.dataValues.model).then(function(result) {
            console.log('This is your result:', result);                
        });
    } else {
        res.status(204).send();
    }
});

您可以简化模型声明:

morphTo: function(models, model_id, model){ 
    if(model == 'medics'){
        return models.medics.findById(model_id);
    }else if(model == 'employees'){
        return models.employees.findById(model_id);
    }
}