Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda