Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get creation date from object id in mongoose?

Tags:

I understand from ObjectId — MongoDB Manual that the first 4 bytes of any mongodb object id is the creation timestamp.

Any well supported way of extracting that information from mongoose?

like image 202
FurtiveFelon Avatar asked Nov 12 '12 19:11

FurtiveFelon


People also ask

How can I tell when a document was created in MongoDB?

The _id field contains the date when the document was inserted into the collection. You can use the getTimestamp() method to extract the date from the ObjectId.

What is object ID in Mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

What does find by id return Mongoose?

Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.


2 Answers

I believe ObjectId has a getTimestamp() method; e.g.

_id.getTimestamp() 
like image 170
Kay Avatar answered Oct 16 '22 18:10

Kay


You can create a virtual 'created' property on the mongoose schema that uses the _id to get the creation timestamp. Just add:

YourMongooseSchema.virtual('created').get( function () {   if (this["_created"]) return this["_created"];   return this["_created"] = this._id.getTimestamp(); }); 
like image 21
Jimmy Pauwaert Avatar answered Oct 16 '22 17:10

Jimmy Pauwaert