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

103
Views
Inconsistent string to date conversion in Mongoose

Model:

const fooSchema = new mongoose.Schema({
    fooCreationDate: {
        type: Date
    },
    bar: [{
        barCreationDate: {
            type: Date
        }
    }]
});

const foo = mongoose.model(`foo`, fooSchema);

If we want to search for foo objects that were created between 2022-01-01 and 2022-01-02, we can use the following mongoose query:

foo.find({
    fooCreationDate: {
        $gte: "2022-01-01T00:00:00.000", 
        $lt: "2022-01-02T00:00:00.000"
    }
});

Please note that I'm using strings instead of date objects. The reason is that the query is passed by the client through an AJAX call with dataType: "jsonp". Every date object that is passed like that to the backend is automatically converted to an ISO string. Despite that, the query works without any issues - the find function automatically parses dates represented as ISO strings.

We'd now like to extract every bar object that was created in the same time range, so we'll need to use an aggregation:

foo.aggregate([{
    $unwind: `$bar`,
}, {
    $match: {
        "bar.barCreationDate": {
            $gte: "2022-01-01T00:00:00.000", 
            $lt: "2022-01-02T00:00:00.000"
        }
    }
}]);

Unfortunately, nothing is found despite the fact that the database contains matching bar objects. This can be confirmed by passing Date objects instead of strings to the $match aggregation:

foo.aggregate([{
    $unwind: `$bar`,
}, {
    $match: {
        "bar.barCreationDate": {
            $gte: new Date("2022-01-01T00:00:00.000"), 
            $lt: new Date("2022-01-02T00:00:00.000")
        }
    }
}]);

This query returns some results, so the conclusion is that mongoose accepts ISO date strings in the find function, but can't handle them in the aggregate function. Is there any known workaround? I could, for example, deep-scan every query object passed from the client and search for ISO date strings, then convert them to Date objects, but that's a bit dirty in my opinion. I'm using mongoose v5.6.4 and mongodb v4.2.2.

about 4 years ago · Juan Pablo Isaza
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!