这是我的天气模型:
// Declare schema
var weatherSchema = Schema({
data: {
type: Object
},
date: {
type: String,
required: true
},
created_at: {
type: Date,
default: Date.now,
index: 1
}
});在date字段中,我存储诸如2017-7-1,2017-7-2,2017-7-3等日期。
现在我在这个天气表上有很多文档,比如2017-6-20到2017-7-3。
因此,我只想从2017-7-1检索到2017-7-2的文档:
Weather
.find({})
.where('date').gt('2017-7-1').lt('2017-7-2')
.exec(function (err, docs) {
console.log(docs);
if (err) {
res.set('Content-Type', 'application/json');
return res.sendStatus(-1);
}
if (!docs) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Not weather data found.');
}
// return docs as json.
return res.status(200).json(docs);
});但我得到的是[]。我做错了什么?
有什么想法吗?
编辑:
以上正式格式 不工作,但它适用于以下格式:
var options = {
"date": {
"$gte": start,
"$lt": end
}
}
Weather
.find(options, function (err, docs) {
console.log(docs);
if (err) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
}
if (!docs) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Not weather data found.');
}
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE');
// return docs as json.
return res.status(200).json(docs);
}).select("-created_at -_id -__v");为什么?
发布于 2017-07-03 22:28:01
要比较日期,date字段应该是Date类型。然后你可以搜索如下:
.where('date').gt(new Date('2017-7-1')).lt(new Date('2017-7-2'))或者,如果要将日期用作字符串,可以这样搜索:
.where('date').in(['2017-7-1', '2017-7-2'])此查询将找到具有确切日期字符串(“2017-7-1”或“2017-7-2”)的条目。
https://stackoverflow.com/questions/44893580
复制相似问题