I am a nodeJs developer, I failed to get the list of users, when I tested my code on postman it gives me the error below: User.find is not a function The following is my user.js file
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
}
}
User.init({
username: {
type:DataTypes.STRING,
allowNull: false,
},
email: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
role: {
type:DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
tableName:'users',
modelName: 'User',
});
return User;
};
and this is where it's imported/required
const router = require('express').Router();
let User = require('../models/user');
router.route('/getUser').post((req, res) => {
User.find({})
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ', err));
});
CodePudding user response:
It didn't work, i did as you told me but it gives me back "sequelize id not defined" Also I don't think that the problem is in the model because I have used it before and in the login I used .find and it workedwithout any problem ! this login code :
router.post('/login',async(req,res,next)=>{
const user = await User.findOne({where: {email : req.body.email}});
if(user){
const password_valid = await bcrypt.compare(req.body.password,user.password);
if(password_valid){
token = JWT.sign({isLogin : true,"id" : user.id,"email" : user.email,"username": user.username},"12345678");
res.status(200).json({token :token});
}
else{
res.status(400).json({isLogin : false, error: "password incorrect" });
}
}
else{
res.status(404).json({isLogin : false, error :"User does not exist"});
}
});
CodePudding user response:
The user.js file that you provided is exporting a function that create the User class (and not actually the User model class)
Did you already init this class elsewhere and you are importing the wrong file ?