summaryrefslogtreecommitdiff
path: root/jstests/aggregation/expressions/date_to_string_on_null.js
blob: 15db75bee756c41eaa27e90afbb3b5ff774fb75e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * Tests for the $dateToString expression with the optional 'onNull' parameter.
 */
(function() {
"use strict";

const onNullValue = ISODate("2017-07-04T11:56:02Z");
const coll = db.date_to_string_on_null;
coll.drop();

assert.commandWorked(coll.insert({_id: 0}));

for (let nullishValue of [null, undefined, "$missing"]) {
    // Test that the 'onNull' value is returned when the 'date' is nullish.
    assert.eq(
        [{_id: 0, date: onNullValue}],
        coll.aggregate({
                $project: {
                    date: {
                        $dateToString:
                            {date: nullishValue, format: "%Y-%m-%d %H:%M:%S", onNull: onNullValue}
                    }
                }
            })
            .toArray());

    // Test that null is returned when the 'timezone' is nullish, regardless of the 'onNull'
    // value.
    assert.eq([{_id: 0, date: null}],
              coll.aggregate({
                      $project: {
                          date: {
                              $dateToString: {
                                  date: "2018-02-06T11:56:02Z",
                                  format: "%Y-%m-%d %H:%M:%S",
                                  timezone: nullishValue,
                                  onNull: onNullValue
                              }
                          }
                      }
                  })
                  .toArray());
}

// Test that 'onNull' can be any type, not just an ISODate.
for (let onNullValue of [{}, 5, "Not a date", null, undefined]) {
    assert.eq(
        [{_id: 0, date: onNullValue}],
        coll.aggregate({
                $project: {
                    date: {
                        $dateToString:
                            {date: "$missing", format: "%Y-%m-%d %H:%M:%S", onNull: onNullValue}
                    }
                }
            })
            .toArray());
}

// Test that 'onNull' can be missing, resulting in no output field when used within a $project
// stage.
assert.eq([{_id: 0}],
          coll.aggregate({
                  $project: {
                      date: {
                          $dateToString:
                              {date: "$missing", format: "%Y-%m-%d %H:%M:%S", onNull: "$missing"}
                      }
                  }
              })
              .toArray());
})();