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

488
Views
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 answers
Answer question

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 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!