在MongoDB模型中以dd MMM yyyy格式存储和检索日期 [英] Store and Retrieve Date in dd MMM yyyy format in MongoDB model
问题描述
我有一个MongoDB模型,其中包含一个Date字段,其类型定义为Date.now.任何日期都将转换为ISO日期格式.在模型内部,日期定义为:
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
}
我将当前日期传递为:
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使用以下查询来查询它:
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);
});
尽管有数据,但我仍然得到一个空白的json数组.在表格内部,xDate以YYYY-MM-DD格式存储.
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.
推荐答案
mongo中的日期不存储在ISO字符串中.如果将模型另存为Date.now,它将保存一个新的Date对象,而不是一个ISO字符串.因此,一种简单的查询方法是通过new Date()
对象进行查询.
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.
还要注意,您的查询很难做到正确,因为您将很难获得与存储数据完全相同的日期.我认为对您来说更好的选择是使用$lt
或$gt
过滤器.
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.
新查询应类似于:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...
这篇关于在MongoDB模型中以dd MMM yyyy格式存储和检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!