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

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