Resolve updatedAt timestamp in node.js

Need to verify the correct timestamp format for the query that finds records later for a particular date

Query in the code does not return expected result, it returns nothing.

const dateToMongoSearch = (dateLineFromHistory) => {
  // we get this time stamp from text file
  // 2022-10-06T09:50:04.555+03:00
  return dateLineFromHistory.split(',')[1];
}

//Query itself
updatedAt = dateToMongoSearch(updatedAt);

const query = await Model.find({ 'updatedAt': { 
    $gt: new Date(updatedAt), //.toISOString(), 
    $exists: true 
  } 
}, {
  allowDiskUse: false
}).limit(limit).toArray()

DB snippet (some data is hidden for security reasons and does not affect on this query):

{
    "_id" : ObjectId("128dec47bbd2f73014646ed1"),
    "firstName" : "first",
    "lastName" : "last",
    "email" : "dev+simulator1@mail.net",
    "emailVerified" : true,
    "passwordCreated" : ISODate("2022-10-06T09:50:03.488+0000"),
    <...>
    "apiRequestStatus" : {
        "maxNumOfKeys" : NumberInt(20),
        "status" : "UNSET",
        "createdAt" : ISODate("2022-10-06T09:50:03.488+0000"),
        "updatedAt" : ISODate("2022-10-06T09:50:03.488+0000")
    },
    "state" : {
        "isFrozen" : false,
        "adminEmail" : null,
        "updatedAt" : ISODate("2022-10-06T09:50:03.488+0000")
    },
    "platform" : "XXX",
    "lastLogin" : ISODate("2022-10-06T09:50:03.488+0000"),
    "accountType" : "XXX",
    "beneficialOwnerName" : null,
    "enableTFA" : false,
    "isReviewed" : false,
    <...>
    "popupToShow" : [

    ],
    "marketingRefferal" : {
        "referralCode" : "CCCC-CCCC",
        "advocateReferralCode" : "DDDD-DDDD"
    },
    "isMigratedFromS" : false,
    "password" : "...",
    "__v" : NumberInt(0),
    "createdAt" : ISODate("2022-10-06T09:50:03.555+0000"),
    "updatedAt" : ISODate("2022-10-06T09:50:05.555+0000")
}

and we need updatedAt that is in the end (a root one)

While using the mongo native driver, the time is truncated from the date object

Hi @Dev_INX - Welcome to the community :wave:

I inserted the test document into my test environment and did the query using the official MongoDB Node Driver (Version 4.8.1).

Here’s a snippet of the query portion of the code I had used against my test environment:

async function run() {
    await client.connect();
    console.log("Connected correctly to server");
    const db = client.db(dbName);
    const coll = db.collection("coll");
    try {
		  const query = await coll.find({ 'updatedAt': {
    	  $gt: new Date("2022-01-01"), //.toISOString(),
   		  $exists: true
          	}
		  },
		  {
 		  	allowDiskUse: false
		  }).toArray()
		  console.log(query)
    }
    catch (e) {
        console.dir(`Failed to drop collection: ${e}`);
    }
}

I have passed through a value of new Date("2021-01-01") to the $gt operator as shown above and tried to keep the query portion as close to what you had provided as possible which did return a result below.
The output:

Connected correctly to server
[
  {
    _id: new ObjectId(“128dec47bbd2f73014646ed1”),
    firstName: ‘first’,
    lastName: ‘last’,
    email: ‘dev+simulator1@mail.net’,
    emailVerified: true,
    passwordCreated: 2022-10-06T09:50:03.488Z,
    apiRequestStatus: {
      maxNumOfKeys: 20,
      status: ‘UNSET’,
      createdAt: 2022-10-06T09:50:03.488Z,
      updatedAt: 2022-10-06T09:50:03.488Z
    },
    state: {
      isFrozen: false,
      adminEmail: null,
      updatedAt: 2022-10-06T09:50:03.488Z
    },
    platform: ‘XXX’,
    lastLogin: 2022-10-06T09:50:03.488Z,
    accountType: ‘XXX’,
    beneficialOwnerName: null,
    enableTFA: false,
    isReviewed: false,
    popupToShow: [],
    marketingRefferal: { referralCode: ‘CCCC-CCCC’, advocateReferralCode: ‘DDDD-DDDD’ },
    isMigratedFromS: false,
    password: ‘...’,
    __v: 0,
    createdAt: 2022-10-06T09:50:03.555Z,
    updatedAt: 2022-10-06T09:50:05.555Z
  }
]

Query in the code does not return expected result, it returns nothing.
Regarding the following in your code:

updatedAt = dateToMongoSearch(updatedAt);

Could you log this value and advise the output including the data type? Please also review the Date() documentation in regards to the new Date() function.

If you still require further assistance, please provide the following:

  1. updatedAt variable value in your code when it is executed
  2. Driver version
  3. MongoDB Server Version

Regards,
Jason

3 Likes

Hi Jason!

updatedAt BEFORE executing a query returns 2022-10-06T09:50:04.555+03:00

I get this data from a file in node.js (app requires he file to temporarily store it)
File contents:
users,2022-10-06T09:50:04.555+03:00
and we cut “users,” string => then store the date in updatedAt variable

and we put in updatedAt to query like that => find({updatedAt: new Date(updatedAt})

driver version: 4.10.0 (the latest one for now)

server version on local PC: 4.4 (locally from mongo’s docker container)
server version on remote machine: ~Ubuntu 20+, will write later (I am not maintaining it and do not have access - but it should be not differ too much)

You show in your example that it is only date in query, without time. Does it matter?

typeof updatedAt is string

UPD: Mongo is in MongoAtlas (remote url), and version is 4.4.17

All fixed, thanks. The problem was not only in timestamp but we fixed.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.