This just returns the date in an ISO format but it's a string, I want it in a Date object format in MongoDB.
I have been using this and I tried to search a lot for the same on the web but wasn't able to find anything. Any help is appreciated.
As I showed in my previous comment, try to use extended json v2 syntax. Something like this:
const request = {
date: {
"$date": "2021-10-01T11:55:28.867Z" // This needs a string in ISO format, not a datetime object.
}
}
Note that "$date" is quoted with: "
Your moment object toString() method might not yield in the correct string format.
This might work: toISOString() Check it out here: Moment.js | Docs
You can try canonical format with epoch milliseconds. Moment can convert your date to that easily. I think it is .valueOf() method
Provide an example of your datetime string from table1.selectedRow.data.Date
You need to tell momentjs how to parse your date if you need to convert to string to moment object: Moment.js | Docs
Like:
const myDateTimeString= '24/12/2019 09:15:00';
moment(myDateTimeString, "DD MM YYYY hh:mm:ss");
# Maybe in your case
moment(table1.selectedRow.data.Date, "DD MM YYYY hh:mm:ss").toISOString();
# Maybe full example. I am not sure, I did not test this:
const request = {
date: {
"$date": moment(table1.selectedRow.data.Date, "DD MM YYYY hh:mm:ss").toISOString();
}
}
# OR with canonical mode
const request = {
date: {
"$date": moment(table1.selectedRow.data.Date, "DD MM YYYY hh:mm:ss").valueOf();
}
}
Thank you so much, Gorkhaan! The first code in your message worked for me!!
The toString() function is yielding the correct Date format in MongoDB.
I appreciate all the help! Thank you!