Query on date for posts created the last 24h

前端 未结 2 1711
闹比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: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"}
    });
    

提交回复
热议问题