Home > Blockchain >  TypeError: Cannot read properties of undefined (reading 'id') in Expressjs
TypeError: Cannot read properties of undefined (reading 'id') in Expressjs

Time:01-30

I'm developing a register function in expressjs, but for some reason return me the following message:

 TypeError: Cannot read properties of undefined (reading 'id')

This is my model: Users.ts

interface UserAttributes {
  id: number;
  first_name: string;
  last_name: string;
  password: string;
  email:string;
  token: string;
  description?: string;
  createdAt?: Date;
  updatedAt?: Date;
  deletedAt?: Date;
}

'use strict';
const {
  Model, Optional
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
   class Users extends Model<UserAttributes> {
    public id!: number;
    public first_name!: string;
    public last_name!:string;
    public email!: string;
    public password!: string;
    public token!: string;

  // timestamps!
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
    public readonly deletedAt!: Date;

    static associate(models) {
      // define association here
    }
  }
  Users.init({
    id: {
      type:DataTypes.INTEGER,
      primaryKey:true
    },
    password: DataTypes.STRING,
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    token: DataTypes.STRING,
  }, {
    sequelize,
    modelName: 'Users',
    tableName:'users',
  });
  return Users;
};

And this is the register controller:

async function Register (req:Request, res:Response): Promise<Response> {
  try {
    const {id, first_name, last_name, email, password, token} = req.body;
    await Users.find(email);
    const encrypt: typeof Users = await bcrypt.hash(password, 10);
    const user: typeof Users  = await Users.create({first_name, last_name, email: email.toLowerCase(), password: encrypt});
    const Token: typeof Users = await jwt.sign({user_id: user.id?.toString(), email:user.email}, process.env.TOKEN_SECRET);
    user.token = Token;
    return res.status(200).json(user);
  } catch (error) {
    console.error('User couldnt be registered', error);
  }
};

Error's message was the following: TypeError: Cannot read properties of undefined (reading 'id')

If someone could help me what's the wrong with the code, I'd be really grateful for the help.

Thanks and have a good day.

CodePudding user response:

The error message "TypeError: Cannot read properties of undefined (reading 'id')" is likely caused by the following line of code:

const Token: typeof Users = await jwt.sign({user_id: user.id?.toString(), email:user.email}, process.env.TOKEN_SECRET);

It looks like the user object returned by the Users.create method is undefined, so the user.id property is also undefined and cannot be accessed.

You can try to debug the issue by adding a console.log statement to print the value of user after the create method call.

Another issue is the following line of code

await Users.find(email);

It should be

await Users.findOne({ where: { email } });

The find method is not available in sequelize.

Also, in the Users.init, you have defined firstName, lastName but you are using first_name, last_name in the Register function.

You should make sure that you are passing the correct values to the create method, and that the create method is returning a non-undefined object.

  • Related