日期条件下的Mongoose查询没有结果,MongoDB Shell可以正常工作 [英] Mongoose Queries on Date Condition Have No Results, MongoDB Shell Works

查看:44
本文介绍了日期条件下的Mongoose查询没有结果,MongoDB Shell可以正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为索引"的集合,其中包含符号",价格"和时间戳"字段.

I have a collection called 'indexes' that contains the 'symbol', 'price', and 'timestamp' fields.

我正尝试在此集合中查询带有特定符号"且时间戳大于某些minDate值的项目.

I am trying to query this collection for items with a specific 'symbol', and that have a timestamp greater than some minDate value.

当通过Mongoose查询数据时,如果对时间戳"有条件,我不会得到任何结果.但是查询是在MongoDB Shell中运行的.

When querying the data through Mongoose I am not getting back any results when I have a condition on the 'timestamp'. Yet queries run in MongoDB shell.

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

I created my collection with the following schema:

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

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

In my NodeJS application I am querying the data like this:

    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个结果.

Whenever running this query, regardless of date used, I'm getting back 0 results.

即使我尝试为所有过去的条目运行(时间戳小于或等于当前时间),我仍然会返回0个结果.

Even if I try running it for all past entries (timestamp less than or equal to current time) I still get back 0 results.

    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.
    });

我知道文档存在于我的收藏夹中,如果删除了时间戳"条件,并仅通过符号"进行查询,它将按预期返回(所有)数据.

I know the documents exist in my collection, If I remove the 'timestamp' condition, and query just by the 'symbol', it returns (all) the data, as expected.

    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'括在引号中.

In my NodeJS app I've tried formatting the date value as an ISO String, Unix Timestamp, and wrapping the '$gte' in quotes.

    // 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个文档.

Using all of these in my NodeJS application I still get back 0 documents.

但是,我的查询会按预期从MongoDB shell和"Mongo Management Studio"执行.

However, my query executes as I'd expect from the MongoDB shell, and from the '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" }

我尝试使用类似于此处

    // 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
        }
    });

我也一直在尝试通过查询查询来调试我的模式:

I've also been trying to debug this by checking my schema from the query:

    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)我的架构中的日期"字段有问题吗?

推荐答案

这实际上是一个非常简单的修复程序.

This was actually a really easy fix.

时间戳"值被保存为字符串,而不是日期对象.

The 'timestamp' value was being saved as a String, and not a Date object.

我从MongoDB shell运行以下查询:

I ran the following query from the MongoDB shell:

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

哪个将我所有的旧记录更新为Date's而不是String's,现在查询就可以了!

Which updated all my old records as Date's instead of String's and now the query works!

这篇关于日期条件下的Mongoose查询没有结果,MongoDB Shell可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆