查询过去24小时内创建的帖子的日期 [英] Query on date for posts created the last 24h

查看:60
本文介绍了查询过去24小时内创建的帖子的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期字段"created_at"的模式:

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},
    pos : {latitude: Number, longitude: Number},
    created_by : {type : Schema.Types.ObjectId, ref : "UserSchema"}
});

与此:

Post.pre("save", function (next){
    var currentDate = new Date();

    if(!this.created_at)
    {
        this.created_at = currentDate;
    }
    next();
});

现在我只想在过去24小时内创建帖子,如何查询呢?

Now I only want post created last 24h, how can I query this ?

推荐答案

要获取最近24小时创建的帖子,您可以获取当前时间,减去24小时,并获取要在日期范围查询中使用的开始日期的值:

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);

如果您想进一步了解$gte,请查看以下文章:

If you want to know more about $gte, check the following article:

https://docs.mongodb.org/manual/reference/运算符/查询/gte/


使用 momentjs 库,这可以很简单


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"}
});

这篇关于查询过去24小时内创建的帖子的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆