Questions & Answers

Same date format between MongoDB and JS but they are not equal?

I'm trying to do an action when the date today (via Node.js) and the date value (via MongoDB) is the same. However, I'm not receiving any output from my for loop indicating that there's no match.

Here's how I get the date today (date output is 2023-01-19T00:00:00.000Z):

const d = new Date(new Date().toLocaleString("en-US", { timeZone: "Asia/Hong_Kong" }));
const day = d.getDate();
const month = d.getMonth() + 1;
const year = "2023"; //this is a dummy variable since year is required for Date().
const date = new Date(year + "-" + month + "-" + day);

Here's the users document from MongoDB:

name: "Angelo"
birthday: 2023-01-11T00:00:00.000+00:00 //Date data type

name: "Josh"
birthday: 2023-01-19T00:00:00.000+00:00 //Date data type

Here's the for loop that should trigger success when there's a match, but there's no output. This is my problem.

let users = [];
.forEach((user) => { users.push(user) })
.then(() => {
   for (i = 0; i < users.length; i++) {
      if(users[i].birthday == date) {
         console.log("Success"); //no output on console

Checking users[i].birthday in console shows:

  • 2023-01-19T00:00:00.000Z (Shouldn't this be a match of today's date?)
  • 2023-01-11T00:00:00.000Z
2023-01-18 23:10:15
What happen if you do db.collection("users").find({"birthday" : date})?
2023-01-18 23:10:15
@ray, it outputs: name: "Josh", birthday: 2023-01-19T00:00:00.000+00:00
2023-01-18 23:10:15
I am not an expert in TS/JS, but the query I mentioned should be the expected way to use the db. In this way, you don't need to fetch full collection from the database to your application and perform the filtering at application level.
2023-01-18 23:10:15
@ray, yeah that makes sense. I'll try it again in an hour and will let you know.
Answers(0) :