Store and Retrieve Date in dd MMM yyyy format in MongoDB model

馋奶兔 提交于 2019-12-25 09:10:02

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/43653979/store-and-retrieve-date-in-dd-mmm-yyyy-format-in-mongodb-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!