gpt4 book ai didi

javascript - Sequelize.js/Node.js/Express.js : Tasks. findAll() 返回 TypeError:Cannot read property 'findAll' of undefined

转载 作者:行者123 更新时间:2023-12-03 22:16:43 26 4
gpt4 key购买 nike

代码应该在请求/tasks 时返回一个带有空任务的 JSON 对象,而是返回一条消息错误 - TypeError: cannot read property 'findAll' of undefined。根据消息,错误来源来自 routes >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 });
});
});
};

源代码 > 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);

最佳答案

在文件 routes/tasks.js 第 2 行,在 task 上添加大写;

  const Tasks = app.db.models.Tasks;

那么它应该可以工作。

关于javascript - Sequelize.js/Node.js/Express.js : Tasks. findAll() 返回 TypeError:Cannot read property 'findAll' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60157009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com