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

153
Vistas
checking undefined or null in javascript

I have below method in nestjs.

async findOne(userId: string) {
        const user = await this.userRepository.find({userId});
        if (user) {
            throw new NotFoundException(`User does not exist`);
        }
        return user;
        
    }

this method retunrn an array of object. if value not found in DB it return [{}]. I need to throw exception when it return empty array I mean [{}]. for that I need to put condition in if block when I write user, or user==null or user.length==o in if block , in all the case it is not going inside the if

what modification I need to do in if block?

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

0

I was wondering why you actually need to use find method.

You are trying to get a user based on userId in usersRepository, isn't userId supposed to be unique?

If it's unique then you are getting either an empty array as you described or with only one object in it. Not sure what DB you are using but in any case, findOne method should be there.

It this applies to your case findOne should do the trick

const user = await this.userRepository.findOne({ userId });
if (!user) throw new NotFoundException(`User does not exist`);

return user;

Or if you have to use find and you want to make if statement more readable I suggest using Ramda, lodash or any similar library to keep it cleaner.

With Ramda you could do as following

const [firstUser = {}, ...others] = await this.userRepository.find({ userId });
if(R.isEmpty(firstUser)) throw new NotFoundException(`User does not exist`);

return [firstUser, ...others];

I highly assume that fetched data based on userId is just one record so I believe you can use just like this

const [user = {}] = await this.userRepository.find({ userId });
if(R.isEmpty(user)) throw new NotFoundException(`User does not exist`);

return user;
about 4 years ago · Juan Pablo Isaza Denunciar

0

It looks like you need to check if user is an array with length = 1 where the first element is an empty object. You can do something like this:

const user = await this.userRepository.find({ userId });
if (
  !user ||
  user.length === 0 ||
  (user.length === 1 && Object.keys(user[0]).length === 0)
) {
  throw new NotFoundException(`User does not exist`);
}
return user;

You will need to look into your userRepositoy.find() function to see if there are any other possible values it could return. From your description, it either returns an array of users or an array with a single empty object. However, there may be other failure cases where it returns something different. That part is up to you to make sure you handle those cases properly.

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