Sequelize 错误:findAll 不是函数

问题描述 投票:0回答:1

我是 Sequelize 的新手,一直在尝试查询模型。 当我调用 api 时出现此错误:

Error fetching data: _database_models__WEBPACK_IMPORTED_MODULE_0__.brands.findAll is not a function 

当我使用 POST 方法时,create() 也出现这种错误

如有任何帮助,我们将不胜感激。

提前致谢

-------------------------------------------------------------

这是route.ts文件

import { create_brands, fetch_brands } from "../../../service/dbService";

export const POST = async (req: Request, res: Response) => {
  try {
    const created_brands = await create_brands(req.body);
    return new Response(JSON.stringify(created_brands));
  } catch (err) {
    return new Response(`Error posting data: ${err.message}`, {
      status: 500,
    });
  }
};

export const GET = async (req: Request, res: Response) => {
  try {
    const all_brands = await fetch_brands();
    return new Response(JSON.stringify(all_brands));
  } catch (err) {
    return new Response(`Error fetching data: ${err.message}`, {
      status: 500,
    });
  }
};

dbService.js

import { brands } from "../database/models";

console.log(JSON.stringify(brands));

export async function create_brands({ name }) {
  const createdBrand = await brands.create({
    name: name,
  });
  return createdBrand.dataValues;
}

export async function fetch_brands() {
  const allBrands = await brands.findAll();
  return allBrands;
}

模型/brand.js

const { Model, DataTypes } = require("sequelize");
import connection from "../connection";

class brands extends Model {
  static associate(models) {
    brands.hasMany(models.products, {
      sourceKey: "id",
      foreignKey: "brandId",
      as: "products",
    });
  }
}

brands.init(
  {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    name: DataTypes.STRING,
  },
  {
    sequelize: connection,
    modelName: "brands",
    timestamps: true,
    underscored: true,
  }
);

export default brands;

模型/index.js

const sequelize = require("../connection");
const brands = require("./brands");
const products = require("./products");

export { sequelize, brands, products };

连接.js

const { Sequelize } = require("sequelize");

const sequelize = new Sequelize({
  dialect: "mysql",
  dialectModule: require("mysql2"),
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
});

async function testConnection() {
  try {
    await sequelize.authenticate();
    console.log("Connection has been established successfully.");
  } catch (error) {
    console.error("Unable to connect to the database:", error);
  }
}

testConnection();

module.exports = sequelize;

我尝试更改导入和导出品牌模型,但不起作用

node.js database sequelize.js
1个回答
0
投票

brands.findAll is not a function

这里,findAll是品牌可以使用的功能(如果它是有效的模型)。根据错误,

brands
似乎不是这里的有效模型。如果我们更深入地研究模型代码。

//models/index.js

const sequelize = require("../connection");
const brands = require("./brands");
const products = require("./products");

export { sequelize, brands, products };

在此文件中,您将同时使用 CommonJS 和 ES6M。您能否验证是否可以在您的nodejs项目中使用import和export关键字。我认为这是没有将

brands
识别为模型的主要问题。

static associate(models) {
    brands.hasMany(models.products, {
      sourceKey: "id",
      foreignKey: "brandId",
      as: "products",
    });
  }

此外,还有其他问题。您已在名为

associate
的模型品牌中定义了静态方法。但目前为止这个方法还没有被调用过。所以,这种关系永远不会建立

要与

products
模型建立关系,您需要调用关联方法并传递包含产品模型的对象。在品牌模型文件中,应该是这样的

const { products } = require('../database/models');
brands.associate({ products })

正如您在关联方法中看到的,您正在以

models.product

的方式访问产品模型

除了这样做之外,还有更好的方法来处理模型及其关联。您可以使用以下内容创建

models/index.js

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const sequelize = require('../connection');

const basename = path.basename(__filename);

const db = {};
fs.readdirSync(__dirname)
  .filter(
    (file) => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js' && file.indexOf('.test.js') === -1
  )
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model; // add model in db {}
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) { // associate method is called
    db[modelName].associate(db); // whole db {} passed to method
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

此文件将加载模型目录中的所有模型并将它们添加到数据库对象中。如果可用的话,它还会调用每个模型的关联方法。

如果您看到以下代码,

const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);

它从每个文件动态加载模型,进行函数调用并传递

sequelize
DataTypes
作为参数。因此,要使其工作,您需要使每个模型的文件返回功能。在函数内,返回值应该是模型。所以品牌模型应该定义如下:

模型/brand.js

const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class brands extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      this.belongsTo(models.product);
    }
  }

  brands.init(
  {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    name: DataTypes.STRING,
  },
  {
    sequelize: connection,
    modelName: "brands",
    timestamps: true,
    underscored: true,
  }
);

  return brands;
};

对于所有其他型号也应继续同样的方法。 现在,每当调用以下代码时

require('../models');

这将首先调用 models/index.js 文件并使所有模型在 db 对象中可用。

所以,这是有效的代码

const { brands } = require('../models');
© www.soinside.com 2019 - 2024. All rights reserved.