【问题标题】:How can I query for documents where date is greater than a provided date?如何查询日期大于提供日期的文档?
【发布时间】:2015-04-29 06:24:08
【问题描述】:

我有一个事件集合,其中包含以这种格式存储的事件日期:YYYY-MM-DD。我想查询所有大于给定日期的事件。这是我目前所拥有的:

var eventSchema = mongoose.Schema({
    title : String,
    details : String,
    start_date : String,
    company: {
        type: String,
        ref: 'Company'
    }
});

eventSchema.methods.getUpcomingEvents = function(company_id, cb) {
var date = utils.dateToday(); // returns e.g., '2015-02-26'

return this.model('Event')
    .find({ company: company_id, start_date : {$gte: date} })
    .sort({start_date: 'asc'})
    .exec(function (err, data) {
        if (err) {
            console.log('ERROR = ' + err);
            cb(false, err);
        } else {
            cb(null, data);
        }
    })
};

问题是这个查询是返回在提供的“日期”之前发生的事件。我做错了什么?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    start_date 是 String,如果要进行日期比较,请设置为 Date。

    把架构改成这样;

    var eventSchema = mongoose.Schema({
        title : String,
        details : String,
        start_date : Date,
        company: {
            type: String,
            ref: 'Company'
        }
    });
    

    【讨论】:

    • 有没有办法在保持 'start_date' 为字符串的同时做到这一点?
    • 改成日期类型,几乎总是更好。
    猜你喜欢
    • 2017-02-27
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2020-11-16
    • 2014-07-14
    • 1970-01-01
    相关资源
    最近更新 更多