javascript - Query on date for posts created the last 24h -
i have schema date field "created_at":
var post = new mongoose.schema({ text : string, created_at : {type : date, index : true}, pos : {latitude: number, longitude: number}, created_by : {type : schema.types.objectid, ref : "userschema"} });
with this:
post.pre("save", function (next){ var currentdate = new date(); if(!this.created_at) { this.created_at = currentdate; } next(); });
now want post created last 24h, how can query ?
to posts created in last 24hrs, current time, subtract 24 hours , value of start date use in date range query:
var start = new date(new date().gettime() - (24 * 60 * 60 * 1000)); post.find({ "created_at": { "$gte": start } }).exec(callback);
if want know more $gte
, check following article:
https://docs.mongodb.org/manual/reference/operator/query/gte/
with momentjs library can simply
var start = moment().subtract(24, 'hours').todate(); post.find({ "created_at": { "$gte": start } }).exec(callback);
you define date default function instead of 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"} });
Comments
Post a Comment