草庐IT

node.js - 日期条件下的 Mongoose 查询没有结果,MongoDB Shell 工作

coder 2023-11-03 原文

我有一个名为“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); });

它将我所有的旧记录更新为 Date's 而不是 String's 现在查询有效了!

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

有关node.js - 日期条件下的 Mongoose 查询没有结果,MongoDB Shell 工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  4. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  5. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  8. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  9. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  10. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

随机推荐