【问题标题】:use model in "sequelize" from a controller在控制器的“续集”中使用模型
【发布时间】:2020-07-02 09:47:29
【问题描述】:

我正在使用由 sequelice-cli 创建的模型,但是当我使用它时,我收到一条错误消息。

我正在使用 ORM(续集),当我尝试访问模型的方法时,例如 finOne()findAll()update(),它无法识别它并引发错误,我已经尝试过以另一种方式工作,但它不是正确的方式,我正在使用 sequelize-cli 生成模型

我需要你的帮助!!!

这是我的模型:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class scholarship_student 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) {
      // define association here
    }
  };
  scholarship_student.init({
    id: DataTypes.INTEGER,
    name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    status: DataTypes.ENUM("Activo", "Inactivo")
  }, {
    sequelize,
    modelName: 'scholarship_student',
  });


  return scholarship_student;
};

这是我的控制器

const becadosController = {};
const db = require("../models/index");
const validation = require("../validation");
const scholarship_student = require("../models/scholarship_student");

becadosController.get = async (req, res) => {

  await scholarship_student.findAll()
    .then((student) => {
      res.json(student);
    })
    .catch((err) => {
      console.log(err);
      res.sendStatus(500);
    });
};

错误:

【问题讨论】:

  • 我通常不会这样设置我的模型,但我希望你试试scholarship_student().findAll()

标签: node.js sequelize.js sequelize-cli


【解决方案1】:

您必须设置一个连接配置,然后您将作为参数传递给您的模型实例。 示例:

const connection = new Sequelize(
  yourDatabaseName,
  yourDatabaseUsername,
  yourDatabasePassword,
  {
    host: yourDatabaseHost,
    dialect: 'whateverDialectYouAreUsing', // example 'mssql'
  }
)

然后

await scholarship_student(connection).findAll()
  .then((student) => {
    res.json(student);
  })
  .catch((err) => {
    console.log(err);
    res.sendStatus(500);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多