Timestamp in require format

Hello,

Hope you’re doing good.

I’m trying using current time stamp as an _id in a collection on insertion trigger.
I’m trying to fetch current timestamp in required format,(MM-DD-YY seconds) seconds will be number of seconds in that particular day.

I tried using Date() and Date.Now() and tried referring the documentation as wellDate

But I didn’t got the desire output. My end goal is to use (MM-DD-YY seconds) seconds will be number of seconds in that particular day , as an _id on insertion trigger.

Thank you.

Using timestamps as an _id is definitely an anti-pattern in MongoDB. These are unique across a collection and it would mean that you cant insert more than two documents in the same second. I would highly recommend just using the MongoDB ObjectID. In fact, you can technically get the timestamp of an insertion from the object id since it is a part of the encoding: https://www.mongodb.com/docs/manual/reference/method/ObjectId/

Thank you for the reply. If I need to add a new attribute to collection with value (MM-DD-YY seconds) seconds will be number of seconds in that particular day , how can I do that on Atlas Triggers.

Triggers is just using a function editor with javascript code. So if you want to add a date, you should be able to create one with “new Date()” and use the javascript methods here if you want to store the date as a string: Date Methods Reference

You can also just store the field as a Date which is supported in MongoDB and is most often the better thing to do when storing a date in the database. Your client-side application can be in charge of how it wants to convert a date into a string

1 Like