Node.js到MongoDB:按date查找

从Nodefinddate到MongoDB的问题:

据说MongoDB可能不是存储date对象,而是一个string,但我不知道如何检查,或者如何解决这个问题。

在我的turnys.js文件中:


 exports.findNeededTurnys = function(req, handler) { console.log("findNeededTurnys"); var key; //var arg0 = {$or:[{start:{$lte:new Date()}, $where: "this.users.length == this.seats"}]}; var arg0 = {start:{$lte:new Date()}}; console.log("findNeededTurnys: arg0="+JSON.stringify(arg0)); turnydb.collection('turnys', function(err, collection) { collection.find(arg0, {safe:true}, function(err, result) { if(err) console.log("findNeededTurnys: find: err="+err); console.log("findNeededTurnys: find: result="+JSON.stringify(result)); handler.handle(result); }); }); }; 

日志文件显示来自MongoDB的空结果?


 findNeededTurnys: arg0={"start":{"$lte":"2014-03-31T10:17:48.857Z"}} findNeededTurnys: find: result={} 

在Mongo中,查询工作(在添加新的Date调用者之后,因为驱动程序可能会在js console.log中将其抽象出来):


 > db.turnys.find({"start":{"$lte":"2014-03-31T10:17:48.857Z"}}); > db.turnys.find({"start":{"$lte":new Date("2014-03-31T10:17:48.857Z")}}); { "gId" : ObjectId("5335e4a7b8cf51bcd054b423"), "seats" : 2, "start" : ISODate("2014-03-31T08:47:48.946Z"), "end" : ISODate("2014-03-31T08:49:48.946Z"), "rMin" : 800, "rMax" : 900, "users" : [ ], "_id" : ObjectId("53392bb42b70450000a834d8") } 

//这里是mongo db的示例


 [ { "gId": "5335e4a7b8cf51bcd054b423", "seats": 2, "start": "2014-03-31T08:47:48.946Z", "end": "2014-03-31T08:49:48.946Z", "rMin": 800, "rMax": 900, "users": [], "_id": "53392bb42b70450000a834d8" }, { "gId": "5335e4a7b8cf51bcd054b423", "seats": 2, "start": "2014-03-31T08:47:48.946Z", "end": "2014-03-31T08:49:48.946Z", "rMin": 1000, "rMax": 1100, "users": [], "_id": "53392bb42b70450000a834da" }, ... ] 

你不需要任何这个包装。 date是一个date

 var zeroth = {$or:[ {start: new Date(), {users:{$size:2}} ]}; 

当然,如果文档中的“date”实际上是“string”而不是适当的datetypes,那么这就是你的问题。 而你真正需要的是修正这些值,所以他们是真正的date。

这适用于任何语言实现,您应该使用本机“date”types,并让驱动程序为您做转换。

如何确定字段是否是string

那么明显的区别就是当你在mongo shell中查看一个文档,如果它是一个真正的BSONdatetypes,那么它看起来像这样:

 "start": ISODate("2014-03-31T08:47:48.946Z"), 

如果这不够清楚,那么你可以在这样的查询中使用$type操作符:

 db.collection.find({ "start": { "$type": 2 } }).count() 

如果它是一个string, 也不是 MongoDB,而是在应用程序或导入中负责创build它的错误实现。 在最初的回应中,这就是关于什么的问题。