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

197
Vistas
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 Respuestas
Responde la pregunta

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 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