这个while循环有什么问题?

时间:2016-04-02 17:18:35

标签: javascript loops

我有一个函数可以过滤mongoDB集合中的文档,并返回日期与星期五,星期六或星期日相匹配的所有结果。这表现得如预期。但是,现在我需要匹配这些结果以确定它们是否会在周末到来,但是我的while循环只返回一个结果,它应该返回三个。出了什么问题?

min_date = max(df.first_valid_index() for df in [o, g])
max_date = min(df.last_valid_index() for df in [o, g])

o = o[(o.index >= min_date) & (o.index <= max_date)]
g = g[(g.index >= min_date) & (g.index <= max_date)]

预期结果:

//FIND ALL ENTRIES THAT FALL ON A WEEKEND
function weekendPlans(callback) {
  Entry.aggregate(
      [
          { "$redact": {
              "$cond": {
                  "if": {
                      "$or": [
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 6 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
                      ]
                  },
                  "then": "$$KEEP",
                  "else": "$$PRUNE"
              }
          }}
      ],
      // GET THE RESULTS AND RETURN IF selectedDate MATCHES THIS WEEKEND
      function(err,results) {
        var i = results.length;
        var theWeekend;
        console.log(results)

        // EVERYTHING WORKS UNTIL HERE
        while(i--) {
          if(results[i].selectedDate === friday || saturday || sunday) {
              theWeekend = results[i];
              //console.log(theWeekend);
              break;
          }
        }
        callback(err, theWeekend)
      }
)};

目前的结果:

[ { _id: 56fffb6ceb76276c8f39e3f4,
    url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
    title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
    selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
    __v: 0 },
  { _id: 56fffb8eeb76276c8f39e3f5,
    url: 'https://news.ycombinator.com/item?id=11404770',
    title: 'The Trouble with CloudFlare | Hacker News',
    selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
    __v: 0 },
  { _id: 56fffb5ceb76276c8f39e3f3,
    url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
    title: 'Where To Eat And Drink In... Balham  | Londonist',
    selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
    __v: 0 } ]

1 个答案:

答案 0 :(得分:0)

更改

results[i].selectedDate === friday || saturday || sunday

~results[i].selectedDate.indexOf('Fri') || 
~results[i].selectedDate.indexOf('Sat') || 
~results[i].selectedDate.indexOf('Sun')

因为您需要使用值检查每个变量,并且日期字符串是否在日期字符串中。