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?
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.
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.
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.
_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.
I believe ObjectId has a getTimestamp() method; e.g.
_id.getTimestamp()
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With