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

86
Views
Mongoose complex query

Using mongoose. The Schema looks similar to this:

{
  "name" : String,
  "start" : Date, 
  "stop" : Date
}

What I'm trying to do, is to build a query, that ("AND"):

  1. "name" == value
  2. "start" - not exists OR "start" gte value
  3. "stop" - not exists OR "stop" lte value

On the other hand, start and stop can be passed, or can be not passed (any of them).

All my attempts for while finished with some kind of Mongo Error :) So asking for some help.

Regards.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your AND query logic can be expressed in either of the two ways :

Implicit AND operation:

Model.find({
    "name": name,
    "start": { 
        "$or": [
            { "$exists": false },
            { "$gte": start } 
        ]
    },
    "stop": { 
        "$or": [
            { "$exists": false },
            { "$gte": stop } 
        ]
    }
}).exec(callback);

Explicit AND operation:

Model.find({
    "$and": [
        { "name": name },
        {
            "start": { 
                "$or": [
                    { "$exists": false },
                    { "$gte": start } 
                ]
            }
        },
        {
            "stop": { 
                "$or": [
                    { "$exists": false },
                    { "$gte": stop } 
                ]
            }
        }
    ]
}).exec(callback);
over 4 years ago · Santiago Trujillo 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!