2015-09-06 63 views
0

找到我想创建在猫鼬查询来实现这一功能:查询通过计算日期

猫鼬型号:

Planted_crop: owner: id, date_planted: Date, crop: id, quantity: Number 
Crop: name: String, water_consumption: Number, grow_time: Number (means hours) 

现在我想获得的所有种植作物AREN”牛逼完全长大呢,在半码,这将是它:

if (plantedCrop.date_planted < plantedCrop.date_planted + plantedCrop.crop.grow_time) { 
    // this crop should be selected 
} 

现在我需要把这种对MongoDB的:

var PlantedCrop = mongoose.model("planted_crop"); 
PlantedCrop.find({ 
    date_planted: { 
     $lt: { 
      date_planted + crop.grow_time * 3600 
     } 
    } 
}).populate("crop").exec(function(err, crops) { 
    // calculate water consumption 
    var consumption = 0, planted; 
    for (var i = 0; i < crops.length; i++) { 
     planted = crops[i]; 
     consumption += planted.crop.water_consumption * planted.quantity; 
    } 
    console.log("Water consumption of planted crops is " + consumption + " liters. 
}); 

我被困在创建这样的查询,任何人都可以帮助我吗?

回答

0

你不应该这样做,因此答案的最佳部分将解释你为什么不想要这种方法。相反,你应该计算GROP将在创建时生长的时间,而这其实只是维持一个额外的字段中(只显示必要的字段):

var date = new Date(); 

PlantedCrop.create({ 
    "owner": ownerId, 
    "crop": cropId, 
    "date"_planted": date, 
    "grow_time": (1000 * 60 * 60) * 2, // "milliseconds" for two hours 
    "ready_time": new Date(date.valueOf() + (1000 * 60 * 60) * 2) 
}); 

然后发现,如果该作物不目前“完全成长”从目前的时间是非常简单:

PlantedCrop.find({ "ready_time": { "$gte": new Date() } },function(err,crops) { 

}); 

如果你想要的东西,是“准备”从当前日期起1小时,然后你只是做:

PlantedCrop.find({ 
    "ready_time": { 
     "$gte": new Date(Date.now + (1000 * 60 * 60)) 
    } 
},function(err,crops) { 

}); 

这在功能上很简单,不会令人困惑,因为所有信息都是在写入时记录的,您只需查看它是否设置了它即可。

的“危险”,在计算方面的思考,这是你开始对使用类型的查询与领域的JavaScript的评价活动:

PlantedCrop.find({ 
    "$where": function() { 
     return this.date_planted.valueOf() + grow_time > Date.now; 
    } 
},function(err,crops) { 

}); 

这是非常糟糕为这样的测试不能使用索引进行搜索,并且会“蛮力”尝试匹配集合中的每个文档。

这就是你想要避免的,以及你希望在处理逻辑中保持干净的东西,但另一种选择是在创建请求时在客户端上运行数学。简单地向后工作,并检查该作物种植“不到一个小时”前,和成长的时间,其实是更大:

PlantedCrop.find({ 
    "date_planed": { 
     "$lte": new Date(Date.now - (1000 * 60 * 60)) 
    }, 
    "grow_time": { "$gte": (1000 * 60 * 60) } 
},function(err,crops) { 

}); 

这会找到你所有的庄稼“没有完全长”的时间框架内你问。

但是至于原来的观点,它看起来很笨重和丑陋,而且只是简单地通过存储最终计算日期并单独查询它来修复。

另请确保所有这些数据都在一个集合中,就像开始时所建议的一样。您不能在这样的查询中引用来自填充项的值,因为这被称为“加入”,MongoDB不会这样做。人口只是通过执行另一个查询来“替代”对象引用,以便在完成初始查询之后用“整个对象”替换那些对象引用。