【问题标题】:Store and Retrieve Date in dd MMM yyyy format in MongoDB model在 MongoDB 模型中以 dd MMM yyyy 格式存储和检索日期
【发布时间】:2017-05-03 15:36:22
【问题描述】:

我有一个 MongoDB 模型,其中包含一个日期字段,其类型定义为 Date.now。任何日期都将转换为 ISO 日期格式。在模型内部,日期定义为:

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

我将当前日期传递为:

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);

但是,日期在 MongoDB 架构中存储为 ISO 字符串。我尝试使用 Mongoose 使用以下查询对其进行查询:

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);
});

尽管数据在那里,但我一直得到一个空白的 json 数组。在表格内,xDate 以 YYYY-MM-DD 格式存储。

【问题讨论】:

    标签: mongodb express mongoose mean-stack


    【解决方案1】:

    mongo 中的日期不存储在 ISO 字符串中。如果您将模型保存为 Date.now,它将保存一个新的 Date 对象,而不是 ISO 字符串。因此,一种简单的查询方法是通过new Date() 对象进行查询。

    另请注意,您的查询很难为真,因为您很难获得与存储数据完全相同的日期。我认为对你来说更好的选择是使用$lt$gt 过滤器。

    新查询应该类似于:

     let currDate = new Date()
     // change the date using class methods
     X.find({
         xDate: {$lt: currDate}
     }).exec...
    

    【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    相关资源
    最近更新 更多