简体   繁体   English

流星db.find在JSON内的日期作为选择器不起作用

[英]Meteor db.find with Date inside a json as selector not working

I read thru a lot of resources in the internet and followed a lot of examples on how to find a collection within a specific date range and it didn't work. 我在互联网上浏览了很多资源,并跟随了很多示例,这些示例说明如何在特定日期范围内找到一个收藏夹,但是它没有用。 My code is as below:- 我的代码如下:

var fromAge = 18;
var toAge = 22;
Meteor.users.find({:profile.birthday":{$lt: new Date(new Date().setYear(new Date().getFullYear() - fromAge)), $gt: new Date(new Date().setYear(new Date().getFullYear() - toAge))}).fetch();

The above query return an empty collection when I do a simple Meteor.users.find().fetch() it did returned one record below:- 当我执行一个简单的Meteor.users.find()。fetch()时,上面的查询返回一个空集合,它确实返回了以下一条记录:-

{"_id": 123452345, "profile.birthday": ISODATE("1975-10-22T00:00:00Z")}

to debug, I also write the following query on both javascript console as well as backend server mongo shell and it did return empty collection as well. 要进行调试,我还在JavaScript控制台和后端服务器mongo shell上都编写了以下查询,它也返回了空集合。

Javascript Console Javascript控制台

Meteor.users.find({"profile.birthday": {$lt: new Date()}})

Server MongoDB Shell 服务器MongoDB Shell

db.users.find{"profile.birthday": {$lt: new Date()}})

I have no clue now. 我现在不知道了。 It would be great if somebody can enlighten me. 如果有人能启发我,那就太好了。

-- UPDATE -- - 更新 -

I tried the below query and it did return nothing 我尝试了以下查询,但没有返回任何内容

db.users.find({"profile.birthday":{$lt: new Date(new Date().setYear(new Date().getFullYear() - 18)).toISOString()}})

I typed in the command in javascript console 我在javascript控制台中输入了命令

new Date(new Date().setYear(new Date().getFullYear() - 18)).toISOString()

And it did tell me 它确实告诉我

"1997-11-06T16:35:28.844Z"

And it my database, the record the birthday should be "1975-10-22T00:00:00Z" and thus it should hit this record, but all I can have is an empty collection. 在我的数据库中,生日记录应该为“ 1975-10-22T00:00:00Z”,因此它应该达到此记录,但是我所能拥有的只是一个空集合。

Someone tells me to use ISODate(), I tried the below command it did works in MongoDB Shell, while it yields ISODate Undefined in my Meteor helper function. 有人告诉我使用ISODate(),我尝试了以下命令在MongoDB Shell中确实起作用,同时在Meteor帮助函数中产生了ISODate Undefined。

db.users.find({"profile.birthday":{$lt: ISODate("1977-11-06")})

Have read thru some other resources ( Inserting and Querying Date with MongoDB and Nodejs ) and learnt that I should use Date instead of ISODate whereby ISODate is internal to MongoDB and Meteor will help to do the Date to ISODate Conversion. 阅读了其他一些资源( 使用MongoDB和Nodejs插入和查询日期 ),并了解到我应该使用Date而不是ISODate,因为ISODate是MongoDB的内部组件,Meteor将帮助完成Date到ISODate的转换。 I then tried to hard code the query and it did works fine:- 然后,我尝试对查询进行硬编码,但效果很好:-

db.users.find({"profile.birthday": {$lt: new Date("1977-11-06T00:00:00.000Z")}})

-- UPDATE BEGIN (16 Nov 2015) -- - 更新开始 (2015年11月16日)-

It works fine, while my problem is I tried to build the selector in json and then put it into the find while this wont work:- 它工作正常,而我的问题是我尝试在json中构建选择器,然后将其放入查找中,而这将无法工作:-

selector={"profile.birthday": {$lt: new Date("1977-11-06T00:00:00:000Z"}};
db.users.find(selector);

The above query returned nothing at all. 上面的查询什么都没有返回。

-- UPDATE END (16 Nov 2015) -- - 更新结束 (2015年11月16日)-

I am doing that because I have a dropdown of age group and am trying to build the query thru a helper event. 我这样做是因为我有一个年龄段下拉列表,并且正在尝试通过一个辅助事件来构建查询。 I have a dropdown template below:- /client/ageRangeDropdown.html 我在下面有一个下拉模板:-/client/ageRangeDropdown.html

<template name="AgeRangeDropdown">
  <div class="btn-group">
    Age Group
    <select id="ageRangeDropdownList" class="form-control">
      <option >Whatever</option>
      <option >18-22</option>
      <option >23-27</option>
      <option >28-32</option>
      <option >33-37</option>
      <option >38-42</option>
      <option >43-47</option>
      <option >48-52</option>
      <option >53-57</option>
    </select> 
  </div>
  {{#each currentCriterias}}
    <span class="label label-info">{{criteria}}</span>
  {{/each}}
  {{#each myUser}}
    {{profile.firstName}} ,  {{profile.lastName}}, {{profile.birthday}}
  {{/each}}
</template>

And the helper below 还有下面的助手

/client/ageRangeDropdown.js /client/ageRangeDropdown.js

Template.ageRangeDropdown.events({
  'change ageRangeDropdownList': function(e) {
  for (var key in target) {
    if (!target.hasOwnProperty(key)) {
      if (key=='id') {
        id = target[key];
      }
    }  
  }
  var value = target.options[target.selectedIndex].value;
  if (value!='Whatever') {
    currentCriterias.push({id: "profile.birthday", criteriaValue: value});
  }
  var query = [];
  for (var i = 0; i < items.length; i++) {
    var itemObject = {};
    var fromAge = currentCriterias[i]['criteriaValue'].substr(0,2);
    var toAge = currentCriterias[i]['criteriaValue'].substr(3,2);
      itemObject['profile.birthday'] = {
        $gt: new Date(new Date().setYear(new Date().getFullYear() - fromAge)),
        $lt: new Date(new Date().setYear(new Date().getFullYear() - toAge))
      }
    query.push(itemObject);
  }
  var selector  = [];
  selector.push({$or: query});
  Template.instance().selector.set({$or: selector});

  return false;
})

Templage.ageRangeDropdown.created = function() {
  var instance = this;
  instance selector = new RactiveVar([]);

  instance.autorun(function() {
    var selector = instance.selector.get();
    if (typeof selector != 'undefined' && Object.keys(selector).length > 0) {
        var subscription = instance.subscribe('searchUser', selector);
    }
  });

  instance.myUser = function() {
    var selector = instance.selector.get();
    if (typeof selector != 'undefined' && Object.keys(selector).length > 0) {
      return Meteor.users.find(selector, {fields: {profile: 1}});
    }
  }
}

server/serverpublish.js 服务器/ serverpublish.js

Meteor.publish("searchUser", function(selector){
  if (!this.userId) {
      console.log("Cannot search User when you haven't logged in.");
      return null;
  } else {
      if (typeof selector != 'undefined' || Object.keys(selector).length > 0) {
        var user=Meteor.users.find(selector, {fields: {profile: 1}});
        return user;
      } else {
        console.log("won't publish all user profiile when no selector is given");
        return null;
      }
    }
});

The logic is like that, actually I have a lot of dropdown each of which will constitute part of the query, and I setup the query using instance reactive variable so that whenever it changed, meteor will do a meteor.find again. 逻辑是这样的,实际上我有很多下拉列表,每个下拉列表都将构成查询的一部分,并且我使用实例反应变量来设置查询,以便每当更改时,meteor都会再次执行meteor.find。 Every dropdown works fine except this birthday which is a date. 除此生日外,每个下拉列表都可以正常工作。 Anyone have idea what's going wrong? 有人知道出什么事了吗?

Hint: 暗示:

Try the following query format in the mongodb shell. 在mongodb shell中尝试以下查询格式。

db.users.find( 
    {"profile.birthday":{ 
        $gte: ISODate(fromAge),
        $lt: ISODate(toAge)
    }
})

fromAge and toAge should be proper format. fromAgetoAge应该是正确的格式。

From another forum I got an answer. 从另一个论坛我得到了答案。

For details please refer to https://forums.meteor.com/t/meteor-db-find-with-date-inside-a-json-as-selector-not-working/12892/9 有关详细信息,请参阅https://forums.meteor.com/t/meteor-db-find-with-date-inside-a-json-as-selector-not-working/12892/9

In short, I just new a Date Object in the query like that 简而言之,我只是在查询中新建了一个Date对象

query[DBPrefix] = {
  $lte: new Date(fromDate),
  $gte: new Date(toDate)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM