Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!