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

224
Visualizações
Is there specific way to do an if-else statement in javascript for mongodb using mongoose?

I want to only run a statement only if the object is not null. If it is null I want to not do anything. I want to be sure if there is a proper way to achieve this. For example I tried it on MongoDB Playground and it did not work. Here is the link to playground: https://mongoplayground.net/p/yOmRxML88zi

Here is the if-else statement I want to run:

    db.collection.aggregate([
       {...},
       service_type ? { $match: { serviceType: service_type } } : null,
       {...},
]);

So if the service_type is not null run the statement else skip to next object in the aggregation. What I want to do in this occasion is get the list of everything in database (objects) that contain certain service type given by the user.

The schema looks something like this:

const sellerSchema = new mongoose.Schema({
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },

  ...,

  serviceType: [{ String }],
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you're using Mongoose, I suppose you're writing your app using Javascript or TypeScript.

What prevent you, then, from building your query like this?

const aggregatePipeline = [];

if (service_type) aggregatePipeline.push({ $match: { serviceType: service_type }});

...

db.collection.aggregate(aggregatePipeline).exec()
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