node.js - Mongoose 对日期条件的查询没有结果,MongoDB Shell 有效

标签 node.js mongodb date mongoose

我有一个名为“indexes”的集合,其中包含“symbol”、“price”和“timestamp”字段。

我正在尝试查询此集合以查找具有特定“符号”且时间戳大于某个 minDate 值的项目。

当通过 Mongoose 查询数据时,当我对“时间戳”有条件时,我不会返回任何结果。然而查询在 MongoDB shell 中运行。

我使用以下架构创建了我的集合:

    var IndexSchema = new Schema({
        symbol: {
            type: String
        },
        price: {
            type: Number
        },
        timestamp: {
            type: Date,
            default: Date.now
        }
    });

在我的 NodeJS 应用程序中,我正在查询这样的数据:

    var Indexes = mongoose.model('Index');

    var numDays = 7;

    var minDate = new Date();
    minDate.setDate(minDate.getDate() - (numDays));

    Indexes
    .find({'symbol':indexSymbol, 'timestamp': {$gte: minDate} })    
    .sort({'timestamp': 1});
    .exec(function (err, items) {
        console.log("There were %s items returned", items.length); // items.length == 0.
    });

每当运行此查询时,无论使用的日期如何,我都会返回 0 个结果。

即使我尝试对所有过去的条目运行它(时间戳小于或等于当前时间),我仍然得到 0 个结果。

    var now = new Date();

    Indexes
    .find({'symbol':indexSymbol, 'timestamp': {$lte: now} })    
    .sort({'timestamp': 1});
    .exec(function (err, items) {
        console.log("There were %s items returned", items.length); // items.length == 0.
    });

我知道文档存在于我的集合中,如果我删除“时间戳”条件,并仅通过“符号”查询,它会按预期返回(所有)数据。

    Indexes
    .find({'symbol':indexSymbol}) 
    .sort({'timestamp': 1});
    .exec(function (err, items) {
        console.log("There were %s items returned", items.length); // items.length == ~40000.
    });

在我的 NodeJS 应用程序中,我尝试将日期值格式化为 ISO 字符串、Unix 时间戳,并将“$gte”括在引号中。

    // ISODate Format.
    .find({'symbol':indexSymbol, 'timestamp': {$lte: minDate.toISOString()} })    

    // Unix Timestamp
    .find({'symbol':indexSymbol, 'timestamp': {$gte: minDate.getTime() } })

    // Wrapping '$gte' in quotes.
    .find({'symbol':indexSymbol, 'timestamp': {'$gte': minDate } })

在我的 NodeJS 应用程序中使用所有这些,我仍然得到 0 个文档。

但是,我的查询按照我期望的 MongoDB shell 和“Mongo Management Studio”执行。

    // MongoDB Shell Query using minDate.toISOString() value.

    > db.indexes.find({'symbol':'.XBT', 'timestamp': { $gte: '2015-12-09T14:57:58.588Z' } });
    { "_id" : ObjectId("566841cff485eb63b3e10375"), "symbol" : ".XBT", "price" : 421.41, "timestamp" : "2015-12-09T14:58:00.000Z" }
    { "_id" : ObjectId("566841cff485eb63b3e10376"), "symbol" : ".XBT", "price" : 421.45, "timestamp" : "2015-12-09T14:59:00.000Z" }
    { "_id" : ObjectId("56684237f485eb63b3e10378"), "symbol" : ".XBT", "price" : 421.4, "timestamp" : "2015-12-09T15:00:00.000Z" }
    { "_id" : ObjectId("56684237f485eb63b3e10379"), "symbol" : ".XBT", "price" : 421.48, "timestamp" : "2015-12-09T15:01:00.000Z" }
    { "_id" : ObjectId("566842c0f485eb63b3e1037d"), "symbol" : ".XBT", "price" : 421.18, "timestamp" : "2015-12-09T15:02:00.000Z" }
    { "_id" : ObjectId("566842c0f485eb63b3e1037e"), "symbol" : ".XBT", "price" : 421.2, "timestamp" : "2015-12-09T15:03:00.000Z" }
    { "_id" : ObjectId("56684328f485eb63b3e10380"), "symbol" : ".XBT", "price" : 421.26, "timestamp" : "2015-12-09T15:04:00.000Z" }
    { "_id" : ObjectId("56684328f485eb63b3e10381"), "symbol" : ".XBT", "price" : 420.76, "timestamp" : "2015-12-09T15:05:00.000Z" }
    { "_id" : ObjectId("566843b0f485eb63b3e10384"), "symbol" : ".XBT", "price" : 420.47, "timestamp" : "2015-12-09T15:06:00.000Z" }
    { "_id" : ObjectId("566843b0f485eb63b3e10385"), "symbol" : ".XBT", "price" : 420.35, "timestamp" : "2015-12-09T15:07:00.000Z" }
    { "_id" : ObjectId("5668441af485eb63b3e10389"), "symbol" : ".XBT", "price" : 420.19, "timestamp" : "2015-12-09T15:08:00.000Z" }
    { "_id" : ObjectId("5668441af485eb63b3e1038a"), "symbol" : ".XBT", "price" : 420.09, "timestamp" : "2015-12-09T15:09:00.000Z" }
    { "_id" : ObjectId("566844a0f485eb63b3e1038d"), "symbol" : ".XBT", "price" : 420.22, "timestamp" : "2015-12-09T15:10:00.000Z" }
    { "_id" : ObjectId("566844a0f485eb63b3e1038e"), "symbol" : ".XBT", "price" : 420.25, "timestamp" : "2015-12-09T15:11:00.000Z" }
    { "_id" : ObjectId("56684507f485eb63b3e10390"), "symbol" : ".XBT", "price" : 420.27, "timestamp" : "2015-12-09T15:12:00.000Z" }
    { "_id" : ObjectId("56684507f485eb63b3e10391"), "symbol" : ".XBT", "price" : 420.21, "timestamp" : "2015-12-09T15:13:00.000Z" }
    { "_id" : ObjectId("5668458ef485eb63b3e10395"), "symbol" : ".XBT", "price" : 420.25, "timestamp" : "2015-12-09T15:14:00.000Z" }
    { "_id" : ObjectId("5668458ef485eb63b3e10396"), "symbol" : ".XBT", "price" : 420.17, "timestamp" : "2015-12-09T15:15:00.000Z" }
    { "_id" : ObjectId("566845f6f485eb63b3e10398"), "symbol" : ".XBT", "price" : 420.11, "timestamp" : "2015-12-09T15:16:00.000Z" }
    { "_id" : ObjectId("566845f6f485eb63b3e10399"), "symbol" : ".XBT", "price" : 420.16, "timestamp" : "2015-12-09T15:17:00.000Z" }

    // MongoDB Shell Query using minDate.getTime() value.

    > db.indexes.find({'symbol':'.XBT', 'timestamp': { $gte: '1449673802572' } });
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb1"), "symbol" : ".XBT", "price" : 385.56, "timestamp" : "2015-11-07T19:21:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb2"), "symbol" : ".XBT", "price" : 385.86, "timestamp" : "2015-11-07T19:22:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb3"), "symbol" : ".XBT", "price" : 386.17, "timestamp" : "2015-11-07T19:23:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb4"), "symbol" : ".XBT", "price" : 386.43, "timestamp" : "2015-11-07T19:24:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb5"), "symbol" : ".XBT", "price" : 386.51, "timestamp" : "2015-11-07T19:25:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb6"), "symbol" : ".XBT", "price" : 386.39, "timestamp" : "2015-11-07T19:26:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb7"), "symbol" : ".XBT", "price" : 386.45, "timestamp" : "2015-11-07T19:27:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb8"), "symbol" : ".XBT", "price" : 386.45, "timestamp" : "2015-11-07T19:28:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bb9"), "symbol" : ".XBT", "price" : 386.85, "timestamp" : "2015-11-07T19:29:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bba"), "symbol" : ".XBT", "price" : 386.91, "timestamp" : "2015-11-07T19:30:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bbb"), "symbol" : ".XBT", "price" : 387.08, "timestamp" : "2015-11-07T19:31:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bbc"), "symbol" : ".XBT", "price" : 387.29, "timestamp" : "2015-11-07T19:32:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bbd"), "symbol" : ".XBT", "price" : 387.29, "timestamp" : "2015-11-07T19:33:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bbe"), "symbol" : ".XBT", "price" : 387.47, "timestamp" : "2015-11-07T19:34:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bbf"), "symbol" : ".XBT", "price" : 387.42, "timestamp" : "2015-11-07T19:35:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bc0"), "symbol" : ".XBT", "price" : 387.56, "timestamp" : "2015-11-07T19:36:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bc1"), "symbol" : ".XBT", "price" : 387.77, "timestamp" : "2015-11-07T19:37:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bc2"), "symbol" : ".XBT", "price" : 387.86, "timestamp" : "2015-11-07T19:38:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bc3"), "symbol" : ".XBT", "price" : 387.91, "timestamp" : "2015-11-07T19:39:00.000Z" }
    { "_id" : ObjectId("5665dc4ff485eb63b3e04bc4"), "symbol" : ".XBT", "price" : 387.89, "timestamp" : "2015-11-07T19:40:00.000Z" }

我尝试使用类似于 here 的查询生成器语法重构我的查询

    // Using the timestamp condition
    Indexes
    .find({})
    .where('symbol').equals(indexSymbol)
    .where('timestamp').gte(minDate)
    .sort('timestamp')
    .select('symbol price timestamp')
    .exec(function (err, items) {
        if(err) {
            console.log("Error: %s", err);
        } else {
            console.log("There are %s items", items.length); 
            // There are 0 items.
        }
    });

    // Without the timestamp condition
    Indexes
    .find({})
    .where('symbol').equals(indexSymbol)
    // .where('timestamp').gte(minDate)
    .sort('timestamp')
    .select('symbol price timestamp')
    .exec(function (err, items) {
        if(err) {
            console.log("Error: %s", err);
        } else {
            console.log("There are %s items", items.length);
            // There are 47425 items
        }
    });

我还尝试通过检查查询中的架构来调试此问题:

    var query = Indexes
    .find({'symbol':indexSymbol, 'timestamp': {$gte: minDate } })    
    .sort({'timestamp': 1});

    console.log("Query = \n %s", util.inspect(query.model.schema));

输出如下:

        Query =
         { paths:
           { symbol:
              { enumValues: [],
                regExp: null,
                path: 'symbol',
                instance: 'String',
                validators: [],
                setters: [],
                getters: [],
                options: [Object],
                _index: null },
             price:
              { path: 'price',
                instance: 'Number',
                validators: [],
                setters: [],
                getters: [],
                options: [Object],
                _index: null },
             timestamp:
              { path: 'timestamp',
                instance: undefined,
                validators: [],
                setters: [],
                getters: [],
                options: [Object],
                _index: null,
                defaultValue: [Function: now] },
             _id:
              { path: '_id',
                instance: 'ObjectID',
                validators: [],
                setters: [Object],
                getters: [],
                options: [Object],
                _index: null,
                defaultValue: [Function: defaultId] },
             __v:
              { path: '__v',
                instance: 'Number',
                validators: [],
                setters: [],
                getters: [],
                options: [Object],
                _index: null } },
          subpaths: {},
          virtuals: { id: { path: 'id', getters: [Object], setters: [], options: {} } },
          nested: {},
          inherits: {},
          callQueue: [],
          _indexes: [],
          methods: {},
          statics: {},
          tree:
           { symbol: { type: [Function: String] },
             price: { type: [Function: Number] },
             timestamp: { default: [Function: now], type: [Function: Date] },
             _id: { auto: true, type: [Function: ObjectId] },
             id: { path: 'id', getters: [Object], setters: [], options: {} },
             __v: [Function: Number] },
          _requiredpaths: [],
          discriminatorMapping: undefined,
          _indexedpaths: undefined,
          options:
           { id: true,
             noVirtualId: false,
             _id: true,
             noId: false,
             read: null,
             shardKey: null,
             autoIndex: true,
             minimize: true,
             discriminatorKey: '__t',
             versionKey: '__v',
             capped: false,
             bufferCommands: true,
             strict: true,
             pluralization: true },
          _events: {} }

问题:

1) 我是否遗漏了为什么我的查询可以在 MongoDB shell 中运行但不能通过 Mongoose 运行?

2) 我的架构中的“日期”字段是否有问题?

最佳答案

这实际上是一个非常简单的修复。

“时间戳”值被保存为字符串,而不是日期对象。

我从 MongoDB shell 运行了以下查询:

 db.indexes.find().forEach(function (doc) { doc.timestamp = new Date(Date.parse(doc.timestamp.toString())); db.indexes.save(doc); });

这将我的所有旧记录更新为日期而不是字符串,现在查询可以工作了!

关于node.js - Mongoose 对日期条件的查询没有结果,MongoDB Shell 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208807/

相关文章:

javascript - 数组的 Promise 未按预期工作

node.js - 使用 Node 调试器 pkg 在 Atom 中找不到 Node 可执行文件

node.js - 如何使用 Node.js 应用程序的 mongoose 清除 mongoDB

mongodb - QGIS MongoDB 插件

java - 使用吗啡搜索对象数组

powershell - Powershell:将“上次修改时间”与“特定日期”进行比较,并用正确的日期替换

node.js - sinon-mongoose 不能与 sinon 9 一起使用

python - 在 pymongo 的字典中包含 NumberInt

php - PDO 转义斜线

javascript - 字符串在Javascript中反对相同的字符串格式?