I have been trying to get a node.js / mongoose query using a date range in an application and it has not worked. So, I took [the code from the Mongo DB cookbook for date range]: http://cookbook.mongodb.org/patterns/date_range/ and put it into a simple node.js application to see if I could get that to work (with no success).
Here is the code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/tb');
var PostSchema = new mongoose.Schema(
title: String,
author: String,
content: String,
created_on: Date
});
Post = mongoose.model('Post', PostSchema);
var newPost = new Post({
"title" : "A blog post",
"author" : "Mike",
"content" : "...",
"created_on" : new Date()
});
Post.remove({},
function(err) {
console.log("cleared out Posts...");
newPost.save( function (err, record) {
console.log("record saved: " + record);
var start = new Date(2013, 7, 1);
var end = new Date(2013, 8, 1);
Post.find({ },
function( err, result_set1) {
console.log("result without date query: " + JSON.stringify(result_set1));
Post.find({created_on: { $gte: start, $lt: end }},
function( err, result_set2) {
console.log("result with date query: " + JSON.stringify(result_set2));
});
});
});
});
And here are the results. When I don't pass date filters, I get the results, but when I put in the date filters I don't get results back. I really appreciate help in figuring this out.
cleared out Posts...
record saved: { __v: 0,
title: 'A blog post',
author: 'Mike',
content: '...',
created_on: Fri Jul 26 2013 23:07:59 GMT+0000 (UTC),
_id: 51f3014f02fee3c438000001 }
result without date query: [{"title":"A blog post","author":"Mike","content":"...","created_on":"2013-07-26T23:07:59.136Z","_id":"51f3014f02fee3c438000001","__v":0}]
result with date query: []
You're going to feel silly about this, but the month argument when constructing a Date
object like you have there is zero-based.
new Date(2013, 7, 1)
Thu Aug 01 2013 00:00:00 GMT-0600 (MDT)
Your months are off by one (too high). Direct your rage at Brendan Eich.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.