Request for message creation date in the last 24 hours
I have this schema with a date for the "created_at" field:
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"}
});
Wherein:
Post.pre("save", function (next){
var currentDate = new Date();
if(!this.created_at)
{
this.created_at = currentDate;
}
next();
});
Now I only need a post created in the last 24 hours, how can I request this?
+3
source to share
2 answers
To get messages generated in the last 24 hours, you can get the current time, subtract 24 hours, and get the start date value in a 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/
In momentjs library it could be as simple
var start = moment().subtract(24, 'hours').toDate();
Post.find({ "created_at": { "$gte": start } }).exec(callback);
You can also define the default date 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"}
});
+7
source to share
I am trying to code for date range in php + mongodb and it works fine, so try like this.
$time1 = new DateTime('Your Date');
$from = new MongoDate($time1->getTimestamp());
$check_date = date('d-m-Y', strtotime($filter_data['to']));
Your condition looks like this
'created_on'=>array($gt' => $check_date)
-4
source to share