Sequelize 数据库模型回归为 (function [anonymous])

问题描述

我一直在尝试从我的续集数据库模型 Accounts 和 Dogs 中找到一条 findall 路线:

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

但是当我尝试运行应用程序和路由时,它不断返回:TypeError:无法读取未定义的属性“findAll”。 因此,在 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,age: {
            type: DataTypes.INTEGER,35],isNumeric: true,isInt: true,food_requirements: {
            type: DataTypes.STRING,200],friendliness: {
            type: DataTypes.INTEGER,validate: {
                len: [1,5],});

    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,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;
};

我不知道接下来要尝试什么。有没有人知道为什么会发生这种情况以及如何解决它?任何帮助将不胜感激。谢谢

解决方法

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

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

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