myl*_*ord 4 javascript date mongodb node.js bson
从节点到 MongoDB 查找日期的问题:
有人说 MongoDB 可能不会存储 Date 对象,而是一个字符串,但我不确定如何检查,或如何解决这个问题。
在我的 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);
});
});
};
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)
日志文件显示来自 MongoDB 的空结果?:
findNeededTurnys: arg0={"start":{"$lte":"2014-03-31T10:17:48.857Z"}}
findNeededTurnys: find: result={}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)
在 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") }
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)
// 这是 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"
},
...
]
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)
您不需要任何这种包装。日期是一个日期:
var zeroth = {$or:[ {start: new Date(), {users:{$size:2}} ]};
Run Code Online (Sandbox Code Playgroud)
现在当然,如果您文档中的那些“日期”实际上是“字符串”而不是正确的日期类型,那么这就是您的问题。而您真正需要做的是修复这些值,使它们成为真实的日期。
这适用于任何语言实现,您应该使用本机“日期”类型并让驱动程序为您进行转换。
那么明显的区别是当你在 mongo shell 中查看一个文档时,如果它是一个真正的 BSON 日期类型,那么它看起来像这样:
"start": ISODate("2014-03-31T08:47:48.946Z"),
Run Code Online (Sandbox Code Playgroud)
如果这还不够清楚,那么$type您可以在这样的查询中使用运算符:
db.collection.find({ "start": { "$type": 2 } }).count()
Run Code Online (Sandbox Code Playgroud)
这也是没有的MongoDB是这样,如果它是一个字符串,但在应用程序或导入从创建该负责很坏的实现。这就是最初回应中提出的观点的全部内容。
| 归档时间: |
|
| 查看次数: |
5016 次 |
| 最近记录: |