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

497
Visualizações
Store and Retrieve Date in dd MMM yyyy format in MongoDB model

I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :

xDate : {
  type: Date.now,
  required: true
}

I pass the current Date as :

var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);

However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:

X.
 find({
  xDate: curDate
 })
.exec(function(err, doc) {
 var response = {
  status : 200,
  message : doc
 };
 if (err) {
  console.log('Error');
  response.status = 500;
  response.message = err;
 } else if (!doc) {
  console.log("Documents against the date not found in database" ,curDate);
  response.status = 404;
  response.message = {
    "message" : "Documents not found for " + curDate
  };
 }
res
 .status(response.status)
 .json(response.message);
});

I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.

Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.

New query should look something like:

 let currDate = new Date()
 // change the date using class methods
 X.find({
     xDate: {$lt: currDate}
 }).exec...
about 4 years ago · Santiago Trujillo Relatório
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