选择“仅限周末的日期”

Select Dates for Weekends Only

本文关键字:日期 周末 选择      更新时间:2023-10-20

我正试图查询我的mongoDB集合,以返回包含字段selectedDate的文档,并检查日期字符串是否在周末(周六[6]或周日[0])。

如何将字段的值传递给函数进行检查?data返回undefined,但我不确定如何将其正确存储在var中。

查询

Entry.
  find({}).
  where('selectedDate').equals(thisWeekend(data)).
  exec(function(err, entries) {
    console.log('Events on a weeked' + ' ' + entries);
  });

功能

function thisWeekend(data) {
  var today = data.getDay();
  if (today == 6 || today == 0) {
    console.log('WEEKEND BITCHES');
  } else {
    console.log('Not the weekend');
  }
};

你不是那样做的,你是这样做的:

Entry.aggregate(
    [
        { "$redact": {
            "$cond": {
                "if": {
                    "$or": [
                        { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
                        { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
                    ]
                },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }}
    ],
    function(err,results) {
       if (err) throw err;
       // results is weekend days only
    }
)

$redact管道运算符通过逻辑表达式过滤文档,这里使用$dayOfWeek来查找工作日值。

另一种情况是$where表达式,但由于这确实需要JavaScript评估,因此它实际上比聚合操作运行得慢得多。实际上,您应该只将其用于MongoDB 2.4或没有$redact:的早期版本

Entry.find(
    {
        "$where": function() {
            var day = this.selectedDate.getUTCDay();
            return ( day == 6 || day == 0 );
         }
    },
    function(err,results) {
        if (err) throw err;
        // Just weekends
    }
)

您真正应该在UTC日期致电.getUTCDay()的地方。