Search code examples
node.jsmongodbdayjs

Dayjs to JS Date for Mongo


I need to parse a user supplied date in NodeJS. I found answers stating that using built in Date constructor/parse method is not reliable and I should use some library like Moment. I was confused that there are Moment and MomentJS libraries and found that there is a tiny library DaysJS having the same interface. Parsing works fine but I cannot find a way how to get the JS Date object that I need to pass to Mongo. Is there any aother way than extract the unix milliseconds and pass it to Date constructor?

When I pass daysjs instance to Mongo NodeJS driver, it fails:

const day = dayjs('2020-01-02', 'YYYY-MM-DD');
2020-06-07 10:42:33:093 [error]: Request failedThe dollar ($) prefixed field '$L' in 'info.date.$L' is not valid for storage.

This seems to work:

let publishDate = new Date(1000 * dayjs().unix());

Is it the correct way of daysjs with Mongo?


Solution

  • The error you got is because you tried to pass a DayJS object to mongodb, which it doesn't support.

    You can pass a javascript Date object to mongodb. In order to convert a DayJS object to plain javascript Date object you can use .toDate() on the DayJS object

    dayjs('2020-01-02', 'YYYY-MM-DD').toDate()