node.js hasMany 用不是 Sequelize.Model 实例的东西调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44070808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:14:00  来源:igfitidea点击:

hasMany called with something that's not an instance of Sequelize.Model

node.jspostgresqlsequelize.js

提问by Ellebkey

as you guys can see my issue is related to the title description, i created a User Model, and a Foto Model in sequelize, basicly a user can shoot many fotos, but each foto can be related to just 1 user.

正如你们所看到的,我的问题与标题描述有关,我创建了一个用户模型,并在续集中创建了一个照片模型,基本上一个用户可以拍摄很多照片,但每个照片只能与 1 个用户相关。

My User model

我的用户模型

    "use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:true,
      defaultValue:null
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }


    });

  User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})

  return Foto;
}

My foto model

我的照片模型

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');


module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull:true
    },
    position: {
      type: DataTypes.RANGE,
      allowNull: true
    }
  });

  Foto.belongsTo(User, {foreignKey: 'userId'});

  return Foto;
}

回答by Ellebkey

You don't need to declare the association on the Photo Model:

您不需要在 Photo Model 上声明关联:

Foto.belongsTo(User, {foreignKey: 'userId'});

When you have a 1:N relation between models you only need to refer the id from the "1" model, on our case the User model, on the "N" model, Photos. So doing:

当模型之间存在 1:N 关系时,您只需要引用“1”模型中的 id,在我们的例子中是 User 模型,在“N”模型中,Photos。这样做:

User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})

Will create a column on your Foto table with name "userId" that refer to user table. On this way both models are associate as you want.

将在您的 Foto 表上创建一个名称为“userId”的列,该列指的是用户表。通过这种方式,两个模型都可以根据需要进行关联。

回答by Toufiq

You can define relations for both models in one file. It doesn't throw any errors that way.

您可以在一个文件中为两个模型定义关系。它不会以这种方式抛出任何错误。

In your Foto.js, you can try:

在您的 Foto.js 中,您可以尝试:

...

Foto.belongsTo(User);
User.hasMany(Foto);

return Foto;

回答by Dorian Jakov Stern Vukotic

I had a similar problem. Sometimes it can be caused because in your index.js or app.js the files are loaded in a specific order, so for example if you have a relationship between A and B, A loads first and references B, and B in turn references A, the error will be thrown inside the B file because A has not been fully defined/executed yet.

我有一个类似的问题。有时可能是因为在您的 index.js 或 app.js 中文件是按特定顺序加载的,例如,如果您在 A 和 B 之间存在关系,则 A 首先加载并引用 B,而 B 依次引用 A ,错误将被抛出到 B 文件中,因为 A 还没有完全定义/执行。

The solution to this would be to remove all associations from the model files, and inside your app or index.js require them all, and then define their relationships.

对此的解决方案是从模型文件中删除所有关联,并在您的应用程序或 index.js 中要求所有关联,然后定义它们的关系。

Example

例子

const entities = {
  A: require('./src/Entity/A'),
  B: require('./src/Entity/B'),
};
entities.A.belongsToMany(entities.B, {through: 'AB'});
entities.B.belongsToMany(entities.A, {through: 'AB'});

回答by muwonge nicholus

So I was getting this error and it took me some time to deal with the bug. I realised I was getting the Error because I was referencing the model wrongly. Sequelize is case sensitive so if you created the model with UpperCase ensure to keep it uniform throughout your referencing.

所以我收到了这个错误,我花了一些时间来处理这个错误。我意识到我收到错误是因为我错误地引用了模型。Sequelize 区分大小写,因此如果您使用 UpperCase 创建模型,请确保在整个引用过程中保持统一。

I would also point out you could try this out instead

我还要指出你可以试试这个

 User.hasMany(models.Foto ,{as: 'fotos', foreignKey: 'userId'})

回答by Scar Coder

It seems you need to define both ends of the relationship in the file containing the 1 part of the 1:many association. That is, the "User" file in your case.

似乎您需要在包含 1:many 关联的 1 部分的文件中定义关系的两端。也就是说,您的案例中的“用户”文件。

So:

所以:

User.hasMany(Foto); Foto.belongsTo(User);

User.hasMany(Foto); Foto.belongsTo(用户);