gpt4 book ai didi

node.js - 使用 FindOne 按日期范围查询 MongoDb(通过 Nodejs native 驱动程序)

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:32 25 4
gpt4 key购买 nike

我正在尝试使用 FindOne 语句中的日期范围来查询 MongoDb,但我无法让它工作。我正在使用 Nodejs native 驱动程序。我尝试了各种选项,但没有返回预期的记录。

这是我的伪代码 -

console.log(sDate);                    // displays  Fri Jun 20 2014 10:00:00 GMT+1000 (AUS Eastern Standard Time)
var sDateISO = sDate.toISOString();
console.log(sDateISO); // displays 2014-06-20T00:00:00.000Z

// all of these return null object
db.collection('events').findOne(
{ eventStartDate: { $lte: new Date(sDate)}},
function(err, obj) { console.dir(obj); } // displays null
);

db.collection('events').findOne(
{ eventStartDate: { $lte: (sDate) }},
function(err, obj) { console.dir(obj); } // displays null
);

db.collection('events').findOne(
{ eventStartDate: { $lte: new Date(sDateISO) }},
function(err, obj) { console.dir(obj); } // displays null
);

db.collection('events').findOne(
{ eventStartDate: { $lte: (sDateISO) }},
function(err, obj) { console.dir(obj); } // displays null
);

但是,如果我在 RoboMongo 中运行此命令,记录将按预期返回 -

enter image description here

==========

更新

我的问题出在代码的其他地方 - 我在传递给 FindOne 查询的单独参数中遇到类型不匹配问题。

documentation 中所述,并由 Christian P 确认下面,我可以直接在 FindOne 查询中使用我的 Javascript 日期对象 sDate

我使用了 typeOf 函数(找到 here )来确认 sDate 确实是一个 Date 对象。

因此,在检查了实际代码中的所有其他变量后,我在其他地方发现了问题,与 Date 对象/参数无关。

最佳答案

ISODate是 MongoDB shell 中 Date 对象的包装器。 Robomongo 嵌入了与 mongo shell 相同的 JavaScript 引擎,这就是您的查询在 RoboMongo 中工作的原因。

要查询日期范围,您只需在查询中使用 Date 对象即可:

db.collection('events').findOne(
{ eventStartDate: { $lte: sDate}},
function(err, obj) {
console.dir(obj);
}
);

关于node.js - 使用 FindOne 按日期范围查询 MongoDb(通过 Nodejs native 驱动程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24323780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com