我正在尝试使用Sequelize和mysql db创建模型。我正在尝试发布到'/ students / register',它一直给我一个错误,指出findOne不是函数。我试过需要我的sql,但它无法正常工作..我还尝试了类似findAll的其他功能,但仍然无法正常工作。这似乎是问题所在
const Sequelize = require('sequelize');
module.exports = function (sequelize, Sequelize) {
const Stundet = 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 = Stundet;
}
路线
const Student_Info = require("../models/students")
student.post('/register', (req, res) => {
const dataToday = new Date()
const studentData = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created: dataToday
}
Student_Info.findOne({
where: {
email: req.body.email
}
})
.then(student => {
if (!student) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
studentData.password = hash
Student_Info.create(studentData)
.then(student => {
res.json({
status: student.email + 'registered'
})
})
.catch(err => {
res.send('error' + err)
})
})
} else {
res.json({
error: 'Student already registered'
})
}
})
.catch(err => {
res.send('error' + err)
})
})
module.exports = student;
答案 0 :(得分:1)
使用module.exports时,应返回Stundet。您已经导出了整个功能。而且我认为您应该传递DataTypes而不是Sequelize。
类似这样的东西:
module.exports = function (sequelize, DataTypes) {
const Stundet = sequelize.define(
//...
return Stundet;
}
所以在您的路线中才能使用模型:
const Sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;
let sequelize = new Sequelize(...);
const Student = require('../models/students')(sequelize, DataTypes);
答案 1 :(得分:0)
我怀疑您的Student_Info为空。您的应用程序是否成功连接到数据库?它有助于记录...例如
sequelizeDB
.authenticate()
.then(() => {
console.log('Yes! DB Connection);
...
})
.catch(err => {
console.error('No! Unable to connect to DB', err);
});
...和恕我直言,将数据库实例命名为“ sequelize”以外的其他代码时,代码的可读性更好。