gpt4 book ai didi

node.js - Sequelize 无法访问模型的方法(Sequelize 6.5)-无法读取未定义的属性 'findAll'

转载 作者:行者123 更新时间:2023-12-03 22:32:05 24 4
gpt4 key购买 nike

我已经按照 Sequelize 文档,数据库已成功创建,但我无法访问我的模型方法。当我记录 Unit 模型时,它只返回 undefined。 (无法读取未定义的属性“findAll”)。
难道我做错了什么?
Controller 和模型如下所示:
Controller /unit.js

const Unit = require('../models').Unit;
const errorHandler = require('../helpers/error_handler');

exports.findAll = async (req, res) => {
try {
const unit = Unit.findAll();
return res.status(200).send({
status: 200,
response: unit
});
} catch (error) {
req.error = error.message;
return errorHandler.http500(req, res);
}
};

模型/index.js
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter((file) => {
return file.indexOf('.') !== 0 && file !== basename && file.slice(3) === '.js';
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
// const model = require(path.join(__dirname, file))(sequelize, Sequelize);

db[model.name] = model;
});

Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

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

module.exports = db;

模型/unit.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Unit 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
}
}
Unit.init(
{
id_eksternal: DataTypes.STRING,
nama: DataTypes.STRING
},
{
sequelize,
modelName: 'Unit'
}
);
return Unit;
};

最佳答案

我无法发表评论,所以我在这里发布我的答案。我认为您需要在 model.name 行中 console.log db[model.name] = model; 以查看 db 中的内容,以及 Controller 中 require('../models') 之后的其他 console.log 以查看 db 的外观。也许这只是你的模型命名

关于node.js - Sequelize 无法访问模型的方法(Sequelize 6.5)-无法读取未定义的属性 'findAll',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65988337/

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