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

查看:30
本文介绍了查询过去 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);

您还可以使用函数定义日期 default预钩中间件:

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天全站免登陆