Query on date for posts created the last 24h

前端 未结 2 1712
闹比i
闹比i 2021-01-14 09:02

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}         


        
相关标签:
2条回答
  • 2021-01-14 09:11

    I have try following code for date range in php+mongodb and its working 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 is look like this

    'created_on'=>array($gt' => $check_date)
    
    0 讨论(0)
  • 2021-01-14 09:23

    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"}
    });
    
    0 讨论(0)
提交回复
热议问题