TypeError:无法读取未定义的属性'findAll'
findAll
函数出错,但是Connection
成功。
并且还以名称managers
创建数据库。
models / index.js
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./maria/manager.model')(manager);
module.exports=manager;
models / maria / manager.model.js
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true }).sync({force:false});
};
app.js
const express = require('express');
const app = express();
const db = require('./models');
console.log(`Checking database connection...`);
// It works!
db.authenticate().then(()=>{
console.log('Database connection OK!');
});
// It makes error!
const find_test = db.manager.findAll();
console.log(find_test);
答案 0 :(得分:0)
首先包含manager
变量的内容是什么?
您的manager
变量包含连接序列。您的目标是请求表manager
,但不能使用变量来请求它。因为他不包含表规范,但包含数据库连接。
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
return sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true });
};
在此文件中,您需要返回表的定义。
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
const myTable = require('./maria/manager.model')(manager);
module.exports= {
manager, myTable
};
在此文件中,您需要将返回值存储在变量中并导出。
const express = require('express');
const app = express();
const { manager, myTable }= require('./models');
console.log(`Checking database connection...`);
// It works!
manager.authenticate().then(()=>{
console.log('Database connection OK!');
});
const find_test = myTable.findAll();
console.log(find_test);
最后在下一个文件中,导入新的导出变量!享受吧!
答案 1 :(得分:0)
app.js
const maria = require('./sequelize');
const { models } = require('./sequelize');
console.log(`Checking database connection...`);
maria.authenticate()
.then(()=>{
console.log('Database connection OK!');
});
const test = models.manager.findOne()
sequelize / index.js
const { Sequelize } = require('sequelize');
const maria = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxxx',
password: 'xxxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./models/manager.model')(maria)
module.exports=maria;