【问题标题】:Sequelize database model are coming back as (function [anonymous])Sequelize 数据库模型将作为(函数 [匿名])回归
【发布时间】:2021-03-03 13:41:17
【问题描述】:

我一直在尝试从我的 sequelize 数据库模型 Accounts 和 Dogs 中查找所有路由:

db.Accounts.findAll({
            where: {
                admin:true,
            },
            include: [db.Dogs]
        }).then((dbAdminAcc) => res.json(dbAdminAcc));
    });

但是当我尝试运行应用程序和路由时,它不断返回:TypeError: Cannot read property 'findAll' of undefined。 因此,在为模型文件夹在 index.js 中进行了一些控制台日志之后,我发现所有三个模型的所有模型都在控制台中显示为“模型是 [函数(匿名)]”。这让我根本无法访问数据。

}).forEach((file) => {
      console.log('The file is', file)
      console.log(path.join(__dirname, file))
        const model = require(path.join(__dirname, file));
        console.log('Model is', model) // This is showing a function (anonymous instead of a name like Accounts)
        db[model.name] = model;
    });

    Object.keys(db).forEach((modelName) => {
      console.log('DB with modelname:', (db[modelName]))
        if(db[modelName].associate) {
            db[modelName].associate(db);
       

} });

我查看了 Dogs 和 Accounts 模型中的语法是否正确,以查看是否缺少返回,但两个模型似乎都设置正确:

module.exports = (sequelize, DataTypes) => {
    
    const Dogs = sequelize.define('Dogs', {
        dog_name: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                len: [2,15],
            },
        },
        breed: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                len: [2,15],
            },
        },
        age: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                len: [2,35],
            },
            isNumeric: true,
            isInt: true,
        },
        food_requirements: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                len: [2,200],
            },
        },
        friendliness: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                len: [1,5],
            },
            isNumeric: true,
            isInt: true,
        }, 
        
    });

    Dogs.associate = (models) => {
        // a Dogs must belong inside the Admin Account
        // Dogs cannot be created without a petId (username) 
        Dogs.belongsTo(models.Accounts, {
            foreignKey: {
                allowNull: false,
            },
        });
    };
    return Dogs;   
};

const bcrypt = require("bcryptjs");

module.exports = (sequelize, DataTypes) => {
    const Accounts = sequelize.define('Accounts', {
      username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
          isUserName: true
        }
      },
      // The password cannot be null
      password: {
        type: DataTypes.STRING,
        allowNull: false
      },
      //this true or false 
      admin: {
        type: DataTypes.BOOLEAN,
        defaultValue: false,
      }
    });
    Accounts.associate = (models) => {
      Accounts.hasMany(models.Dogs, {
          onDelete: 'cascade'
      });
    };

 
  Accounts.prototype.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
  };
 
  Accounts.addHook("beforeCreate", function(accounts) {
    Accounts.password = bcrypt.hashSync(accounts.password, bcrypt.genSaltSync(10), null);
  });
  
  return Accounts;
};

我不知道下一步该尝试什么。有人对为什么会发生这种情况以及如何解决有任何见解吗?任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您缺少带参数的函数调用,即 functionName(arg1, arg2)。只需将要求设为const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); 参考:stackoverflow.com/a/62984731/8133717

标签: sequelize.js sequelize-cli


【解决方案1】:

您应该使用 Sequelize import 函数注册模型,而不是仅使用 require 导入它们:

var model = sequelize['import'](path.join(models, file))
db[model.name] = model

UPD:此 import 方法自 v6 以来已被弃用。使用@Abhishek 在他的评论中指出的方法。 看我的回答here

【讨论】:

  • 此方法 - sequelize.import 自 v6+ 起已被弃用
  • 是的,你说的很对。我会将其添加到我的答案中。同时,您可以根据评论创建您的答案,使其更加独立于版本。
猜你喜欢
  • 1970-01-01
  • 2020-11-16
  • 2022-06-20
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 2011-01-29
相关资源
最近更新 更多