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

196
Visualizações
How can I use modify and use ‘$and’ in a search query when some items are null?

I need help tweaking the code for this:

const posts = await PostMessage.find({ $or: [ { title }, { tags: { $in: tags.split(',') } } ]});

At the moment, you can filter for posts using a search form which has title and posts. You can leave one empty when you search. It works fine except when you use both. For example searching “hiking” and tagging “Europe” would show posts for both hiking titles AND Europe tags (when I would want the search narrowed down to only show posts with the title hiking and tagged Europe). I know that I can use $and in place of $or but that only returns posts if the user enters both title and tags when I want to give the user the option to leave one blank. Can someone help me write out the code for that?

From what I’ve seen I was wondering if I could do something like this:

Or: { (And: title not null, tags not null ) (Or title null, tags not null) (Or title not null, tags null) )

Is this possible to do? I can’t find a similar example. Thanks for the help!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Assuming that none of the parameters (title,tags) will be undefined you can design query before you run it

const query = {
  title: title,
  tags: { $in: tags.split(",") },
};
const params = { title, tags };
Object.keys(params).forEach((param) => {
  if (!params[param]) {
    delete query[param] // delete from query if value is not present
  }
});

const posts = await PostMessage.find(query);

This way it will use only the parameters that have values

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