Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
Error TypeError: Cannot read properties of undefined (reading 'funcao')

Hi everyone i'm creating a site whit javascript and i need authentication to check if is an admin or a customer to redirect him for different ways , but i have a problem , when i try to check the Cannot read properties of undefined.

My AuthorizatioCheck

module.exports =  async function(req, res, next){
if(req.isAuthenticated()){
     const utilizador = req.Utilizador;
     if(utilizador.funcao==='admin'){
         next();
     }else{
          res.redirect('back');
     }
}else{
    res.redirect('/utilizadores/login');
}

};

The model

    const mongoose = require('mongoose');

const utilizadorSchema = mongoose.Schema({

    nome:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    funcao:{
        type: String,
        required: true,
        default: 'customer'
    },

    fidelizacao:{
        type:Number,
        default:0
        

    },
    carrinho:[{
        livro:{
            type: mongoose.Schema.Types.ObjectId,
            ref: "Livro",
        },
        quantidade:{
            type: Number,
            required: true,
            default: 1
        }
    }]
});

module.exports = mongoose.model("Utilizador", utilizadorSchema);

The error

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

at module.exports (C:\Users\cardo\Desktop\book--store--nodejs-master\middleware\checkAuthorization.js:4:24)

Can someone fix me ? i'm watching the code for hours and can't figure out...

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The error means that utilizador (=> req.Utilizador) is undefined and therefore funcao is not a valid property of it.

To fix this specific error I suggest using optional chaining;

if (utilizador?.funcao === 'admin') {
    next();
} else {
    res.redirect('back');
}

Next you should probably check why req.Utilizador is not being defined, assuming it should be in your application logic.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda