Проверьте, находится ли документ между двумя датами, используя Mon goose и MomentJS - PullRequest
1 голос
/ 07 января 2020

Я просмотрел похожие посты, но решения пока не работают, я понятия не имею, что я делаю неправильно. Я попытался отформатировать дату очень разными способами и даже просто использовать библиотеку new Date() помимо момента. Я попытался преобразовать даты, используя .toISOString().

Вот пример документа в коллекции, который я пытаюсь запросить.

[
  {
    "_id": ObjectId("5df58d45244a850d54b922c8"),
    "lessons": [
      {
        "_id": ObjectId("5db221be211d7b68ac8be618"),
        "mentorData": {
          "objective": "Ensuring students that making mistakes is normal and that it is a part of life",
          "task": "Post a video explaining obstacles that you had to overcome as a programmer",
          "dueDate": "2019-12-14T15:26:10.000+0000"
        },
        "studentData": {
          "objective": "Learning that failures help you grow",
          "task": "Post a video explaining obstacles that you have overcame",
          "dueDate": "2020-01-14T22:26:10.000+0000" <---- CHECKING THIS DATE
        },
        "title": "How to overcome obstacles",
        "comments": []
      }
    ]    
  }
]

Я запрашиваю БД следующим образом:

const query = {
  "lessons.studentData.dueDate": {
    $gte: moment()
      .startOf("isoweek")
      .toDate(),
    $lte: moment()
      .endOf("isoweek")
      .toDate()
  }
};

Class.find(query).then(doc => {
  res.json(doc);
});

, который возвращает пример документа , чего не должно быть, потому что ...

lessons.studentData.dueDate единственного документа - 2020-01-14T22:26:10.000+0000, который НЕ находится между следующими $ gte 2020-01-06T06:00:00.000Z и $ lte 2020-01-13T05:59:59.999Z

[
  {
    "_id": ObjectId("5df58d45244a850d54b922c8"),
    "lessons": [
      {
        "_id": ObjectId("5db221be211d7b68ac8be618"),
        "comments": [],
        "mentorData": {
          "dueDate": "2019-12-14T15:26:10.000+0000",
          "objective": "Ensuring students that making mistakes is normal and that it is a part of life",
          "task": "Post a video explaining obstacles that you had to overcome as a programmer"
        },
        "studentData": {
          "dueDate": "2020-01-14T22:26:10.000+0000",
          "objective": "Learning that failures help you grow",
          "task": "Post a video explaining obstacles that you have overcame"
        },
        "title": "How to overcome obstacles"
      }
    ]
  }
]

1 Ответ

1 голос
/ 07 января 2020

Судя по вашему коду, вы пытаетесь получить документы за текущую неделю:

let startDate = moment().startOf("isoweek").format('YYYY-MM-DD'); //2020-01-06
let endDate = moment().endOf("isoweek").format('YYYY-MM-DD'); //2020-01-12

Class.aggregate([
    { $unwind: '$lessons' },
    { $addFields: { 'date': { $dateToString: { format: "%Y-%m-%d", date: "$lessons.studentData.dueDate" } } } },
    { $match: { $and: [{ 'date': { $gte: startDate } }, { 'date': { $lte: endDate } }] } },
    { $group: { _id: '$_id', lessons: { $push: '$lessons' } } }
])

Примечание: Если вы наберете lessons.studentData.dueDate в ISODate(), тогда это будет Трудно получить эти две входные даты в формате ISODate(), поэтому нам нужно привести lessons.studentData.dueDate и ввести даты в один и тот же формат и сравнить их, поскольку dueDate находится в массиве, который мы раскручиваем и преобразуем перед сравнением.

Ссылка: $ dateToString

Данные сбора:

/* 1 */
{
    "_id" : ObjectId("5df58d45244a850d54b922c8"),
    "lessons" : [ 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be618"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-06T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-01T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-15T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("5df58d45244a850d54b922d8"),
    "lessons" : [ 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be618"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-16T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-18T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-15T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("5df58d45244a850d54b923c8"),
    "lessons" : [ 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be618"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            }
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            }
        }, 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be628"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            }
        }
    ]
}

/* 4 */
{
    "_id" : ObjectId("5e1403ba627ef78236d1505d"),
    "lessons" : []
}

Результат:

/* 1 */
{
    "_id" : ObjectId("5df58d45244a850d54b922c8"),
    "lessons" : [ 
        {
            "_id" : ObjectId("5db221be211d7b68ac8be618"),
            "mentorData" : {
                "objective" : "Ensuring students that making mistakes is normal and that it is a part of life",
                "task" : "Post a video explaing obstacles that you had to overcome as a programmer",
                "dueDate" : ISODate("2019-12-14T15:26:10.000Z")
            },
            "studentData" : {
                "objective" : "Learning that failures help you grow",
                "task" : "Post a video explaining obstacles that you have overcame",
                "dueDate" : ISODate("2020-01-06T22:26:10.000Z")
            },
            "title" : "How to overcome obstacles",
            "comments" : []
        }
    ]
}
...