我确实提到了类似的问题,例如this,但是在调试时,我得到models
为空。我不知道为什么会这样。数据库表为Users
。
controllers / user.js:
const models = require('../models');
const User = models.Users;
exports.getAllUsers = (req,res,next) => {
console.log(models);
console.log(User);
User.findAll({
attributes: attributesUser
}).then(users => {
console.log(users);
res.status(200).json({
data: users
});
});
}
models / user.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
firstName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [4, 255]
}
},
middleName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [4, 255]
}
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [4,255]
}
},
mobile: {
type: DataTypes.STRING,
validate:{
len: [10,15],
isNumeric:{
msg:"Invalid Mobile Number"
}
}
},
address: {
type: DataTypes.STRING,
allowNull:false
},
dob: {
type: DataTypes.DATEONLY,
allowNull:false
},
email: {
type: DataTypes.STRING,
allowNull:false,
unique: true,
validate: {
isEmail: true
},
set(email){
this.setDataValue("email",email.toString().toLowerCase());
}
},
password: {
type: DataTypes.STRING,
allowNull:false
},
gender: {
type: DataTypes.STRING,
allowNull:false
},
isDisabled: {
type: DataTypes.BOOLEAN,
allowNull: false
},
lastLoginTime: {
type: DataTypes.DATE,
},
createdAt: {
type: DataTypes.DATE,
allowNull:false
},
updatedAt: {
type: DataTypes.DATE,
},
deletedAt: {
type: DataTypes.DATE,
},
}, {});
Users.associate = function(models) {
// associations can be defined here
Users.belongsTo(models.UserType, {
foreignKey: {
name: "userTypeId",
allowNull: false
}
});
Users.belongsTo(models.Qualification, {
foreignKey: {
name: "qualificationId",
allowNull: false
}
});
Users.belongsTo(models.Organization, {
foreignKey: "organizationId",
allowNull: false
});
};
return Users;
};
输出:
TypeError: Cannot read property 'findAll' of undefined
at exports.getAllUsers (/mnt/part1/projects/Video_Coaching/backend-v2/controllers/user.js:87:10)
at Layer.handle [as handle_request] (/mnt/part1/projects/Video_Coaching/backend-v2/node_modules/express/lib/router/layer.js:95:5)
at next (/mnt/part1/projects/Video_Coaching/backend-v2/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/mnt/part1/projects/Video_Coaching/backend-v2/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/mnt/part1/projects/Video_Coaching/backend-v2/node_modules/express/lib/router/layer.js:95:5)
at /mnt/part1/projects/Video_Coaching/backend-v2/node_modules/express/lib/router/index.js:281:22
答案 0 :(得分:0)
问题在于模型没有序列化实例。
虽然sequelize在models /下创建了一个index.js文件,但我在项目开始时就评论了该文件,因为它给了我错误。我只是取消注释该文件并创建了const models = require('../models/index');
这样的模型。
因此,应该要求models/index.js
获得将要使用模型而不是models/user.js.
的sequelize和DataTypes实例