Sequelize.js / Node.js / Express.js:Tasks.findAll()返回TypeError:无法读取未定义的属性'findAll'

时间:2020-02-10 19:20:01

标签: javascript node.js express sequelize.js babeljs

当请求/ tasks时,

code应该返回一个带有空任务的JSON对象,而是返回一条消息错误-TypeError:无法读取未定义的属性'findAll'。根据消息显示的错误源来自route> tasks.js,有关沙盒上的屏幕截图或实时代码,请参见下文。

项目文件夹: enter image description here

sandbox

一些代码: src>模型> tasks.js

module.exports = (sequelize, DataType) => {
  const Tasks = sequelize.define(
    "Tasks",
    {
      id: {
        type: DataType.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      title: {
        type: DataType.STRING,
        allowNull: false,
        validate: {
          notEmpty: true
        }
      },
      done: {
        type: DataType.BOOLEAN,
        allowNull: false,
        defaultValue: false
      }
    },
    {
      classMethods: {
        associate: models => {
          Tasks.belongsTo(models.Users);
        }
      }
    }
  );
  return Tasks;
};

src> routes> tasks.js

module.exports = app => {
  const Tasks = app.db.models.tasks;
  app.get("/tasks", (req, res) => {
    Tasks.findAll({}).then(tasks => {//source of error as per error message
      res.json({ tasks: tasks });
    });
  });
};

src> db.js

var path = require("path");

var fs = require("fs");

var Sequelize = require("sequelize");
//const config = require("./libs/config.js");

var sequelize = null;
let db = null;

module.exports = app => {
  if (!db) {
    const config = app.libs.config;
    sequelize = new Sequelize(
      config.database,
      config.username,
      config.password,
      config.params
    );
    db = {
      sequelize,
      Sequelize,
      models: {}
    };
    const dir = path.join(__dirname, "models");
    fs.readdirSync(dir).forEach(file => {
      const modelDir = path.join(dir, file);
      const model = sequelize.import(modelDir);
      db.models[model.name] = model;
    });
    Object.keys(db.models).forEach(key => {
      db.models[key].options.classMethods.associate(db.models);
    });
  }
  return db;
};

src> index.js

var express = require("express");
var consign = require("consign");
var app = express();

consign({ cwd: "src" })
  .include("./libs/config.js")
  .then("db.js")
  .then("./libs")
  .then("./routes")
  .into(app);

1 个答案:

答案 0 :(得分:3)

在文件route / tasks.js第2行中,在任务上添加大写字母;

  const Tasks = app.db.models.Tasks;

然后它应该可以工作。