Home:ALL Converter>How to automatically add server date to a document on insert?

How to automatically add server date to a document on insert?

Ask Time:2021-04-23T07:45:30         Author:Eugen1344

Json Formatter

I am using REST API (RESTHEART) to insert new entries into MongoDB. I have a JSON to insert

{
    "name": "test"
}

When i insert said document, MongoDB automatically creates _id field for my document, which is a good thing. But i also want Mongo (or restheart) to automatically create a field "date" with a current server timestamp. How do i achieve this? I don't want to put a date from client on my server, and i don't want to use the built-in date in "_id" field. I want to have my every database entry to be signed with timestamp on insertion. Oddly enough, i haven't found any way of doing this simple task. Is this even possible? I really don't want to write my own server from scratch just so my users can post JSON documents to my database. I have only managed to insert server date by specifying invalid JSON in my post request.

{
    "name": "test",
    "date": new Date()
}

This works, but this is clearly the bad solution.

Author:Eugen1344,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/67222155/how-to-automatically-add-server-date-to-a-document-on-insert
yy