I have this schema with a date for the field \"created_at\":
var post = new mongoose.Schema({
text : String,
created_at : {type : Date, index : true}
To get posts created in the last 24hrs, you could get the current time, subtract 24 hours and get the value of start date to use in your date range query:
var start = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
Post.find({ "created_at": { "$gte": start } }).exec(callback);
If you want to know more about $gte
, check the following article:
https://docs.mongodb.org/manual/reference/operator/query/gte/
With the momentjs library this can be simply
var start = moment().subtract(24, 'hours').toDate();
Post.find({ "created_at": { "$gte": start } }).exec(callback);
You could also define a date default with a function instead of the pre hook middleware:
var post = new mongoose.Schema({
text : String,
created_at : {type : Date, default: Date.now, index : true},
pos : {latitude: Number, longitude: Number},
created_by : {type : Schema.Types.ObjectId, ref : "UserSchema"}
});