Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda