我正在尝试使用Sequelize和mysql db创建模型。我正在尝试发布到'/ students / register',它一直给我一个错误,指出findOne不是函数。我试过需要我的SQL,但它不工作..我也试过像findAll之类的其他函数,但仍然无法工作。似乎是问题所在。谢谢
models / Students.js
const Sequelize = require('sequelize');
const sequelize = require('../database/db')
module.exports = (sequelize, Sequelize) => {
const Student = sequelize.define(
'student', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
}, {
timestamps: false
});
module.exports = Student;
};
数据库/db.js
const Sequelize = require('sequelize')
const sequelize = new Sequelize('canavs', 'root', 'root', {
host: 'localhost',
port: 8889,
dialect: 'mysql',
operatorAliases: false,
pool: {
max: 5,
min: 0,
acquire: 3000,
idle: 10000
}
})
// sequelize.import('./models/Students')
module.exports = sequelize;
index.js
const Student_Info = require('./models/Students')
const db = require('./database/db')
// app.use('/students', Student)
app.get('/getName', (req, res) => {
Student_Info.findOne({
where: {
id: 1
}
})
.then((student) => {
res.json(student.name);
})
.catch((err) => {
res.send('error' + err)
}
)
})
答案 0 :(得分:0)
在student
模型定义中,您没有返回定义。
module.exports = (sequelize, Sequelize) => {
const Student = sequelize.define(
'student', {
...
}, {
timestamps: false
});
return Student; // You have to return the Student model in its definition
};
希望这对您有帮助...
答案 1 :(得分:-1)
让它保持简单的导出状态,仅学生模型,无需导出Sequelize / sequelize(db)bcoz,您可以要求它而不是导出要求它!
const Sequelize = require('sequelize');
const sequelize = require('../database/db');
const Student = connection.define('student', {
name: Sequelize.STRING,
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
validate: {
isAlpha: true
}
}
});
module.exports = Student;