【发布时间】:2017-01-19 21:15:09
【问题描述】:
所以我对我的 MongoDB 进行了一个非常简单的查询,我想在其中找到所有持续时间高于当前日期的对象。我的查询:
Campaign.find({ 'duration': { $gt: Date.now() } }, function(err, numAffected){
if(err){
console.log(err);
}else{
console.log(numAffected);
console.log(typeof numAffected);
}
});
当我直接在 Robomongo 中运行此查询时,我会得到一个持续时间大于当前时间的对象的预期结果。此外,当使用没有 $gt-tag 的 mongoose 时,我得到了我想要提取的对象。上面的查询给了我一个空的数组对象。
我的猫鼬版本是 2.4.10。
模型中的 Duration 对象如下所示:
duration: {
//How long should the campaign last
type: Date,
default: function(){return +new Date() + 7*24*60*60*1000;},
required: 'Please fill the duration of the Campaign. Default is 1 week.'
},
【问题讨论】:
-
Date.now()方法返回自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数,而duration字段是Date类型,而不是Number因此查询失败。您需要的是一个 Date 对象,它将查询中的当前日期时间表示为Campaign.find({ 'duration': { $gt: new Date() } }, callback) -
也试过了。没有雪茄。
var dateNow = new Date(); Campaign.find({ 'duration': { '$gt': dateNow } }, function(err, numAffected){ -
如果我删除 $Gt 标签,console.log() 我得到所需数据上的持续时间对象
Mon Sep 19 2016 13:04:41 GMT+0200 (CEST) -
问题可能是猫鼬如何存储日期,请参阅stackoverflow.com/a/16665301/224370