在Model.belongsTo中调用的东西不是Sequelize.Model的实例

时间:2016-12-04 17:53:11

标签: javascript node.js sequelize.js

我试图在2个模型之间引用外键。

但我收到此错误:

var result = await UserManager.VerifyChangePhoneNumberTokenAsync(input.UserId, input.Token, input.MobileNumber);

我该如何解决这个问题?

到目前为止,这是我的代码。

这是我的模特/ mercadolibre.js

throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model');
called with something that's not an instance of Sequelize.Model
    at Model.belongsTo

这是我的models / user.js

"use strict";
var User  = require('../models/index').User;

module.exports = function(sequelize, DataTypes) {
  var MercadoLibre = sequelize.define("MercadoLibre", {
    id:  { 
          type: DataTypes.INTEGER, 
          autoIncrement: true, 
          primaryKey: true
        },
    access_token: DataTypes.STRING,
    refresh_token: DataTypes.STRING,
    environment_hash: DataTypes.STRING 
  }, {
    tableName: 'mercadolibres',
    underscored: true,
    timestamps: true
  }

  );

  MercadoLibre.belongsTo(User);

  return MercadoLibre;
};

这是我的models / index.js

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    id:  { 
          type: DataTypes.INTEGER, 
          autoIncrement: true, 
          primaryKey: true
        },
    name: DataTypes.STRING,
    slack_id: DataTypes.STRING,
    environment_hash: {
          type: DataTypes.STRING,
          defaultValue: DataTypes.UUIDV4
        }
  }, {
    tableName: 'users',
    underscored: false,
    timestamps: false
  }

  );

  return User;
};

1 个答案:

答案 0 :(得分:9)

像这样使用:

module.exports = function(sequelize, DataTypes) {
var MercadoLibre = sequelize.define("MercadoLibre", {
   id:  { 
      type: DataTypes.INTEGER, 
      autoIncrement: true, 
      primaryKey: true
    },
    access_token: DataTypes.STRING,
    refresh_token: DataTypes.STRING,
    environment_hash: DataTypes.STRING 
}, {
    tableName: 'mercadolibres',
    underscored: true,
    timestamps: true,
    classMethods: {
        associate : function(models) {
            MercadoLibre.belongsTo(models.User)
        },
      },
  });



return MercadoLibre;

};