SoftInstigate / restheart

Rapid API Development with MongoDB
https://restheart.org
GNU Affero General Public License v3.0
805 stars 171 forks source link

How to insert current date in document #95

Closed singhvikram704 closed 8 years ago

singhvikram704 commented 8 years ago

How to insert current date in document as like $currentdate in mongo

mkjsix commented 8 years ago

Please check if this answers your question: https://github.com/SoftInstigate/restheart/issues/89

singhvikram704 commented 8 years ago

In this answer we passing date from client. I want to insert mongo server's current date as do at shell with $currentDate.

ujibang commented 8 years ago

Hi @singhvikram704

if you want restheart to add a time stamp you can rely on Representation Tranformers

There is a ready to use transformer called addRequestProperties that allows you to inject some useful properties to write requests. Specifically you can add the dateTime property that is the request date.

Note that this solution is much more reliable if you want to make sure that the client doesn't alter somehow the timestamp. In fact using $currentDate is still controlled by the client who could send whatever value.

You can read the documentation for more details, in summary you add the rts metadata property to the collection specifying the addRequestProperties transformer with scope "CHILDREN" and phase "REQUEST" and restheart will use it for the write requests on collection documents.

PATCH /db/coll
{ rts: [
    {
     "name": "addRequestProperties", 
     "phase": "REQUEST", 
     "scope": "CHILDREN",
     "args": { "log": [ "dateTime", "epochTimeStamp" ] }
   }
] }

Now if you add a document to /db/coll you'll see the property being injected.

PUT /db/coll/doc { "a": 1 }
GET /db/coll/doc

HTTP/1.1 200 OK
...

{
    "_id": "doc", 
    "a": "1", 
    "log": {
        "dateTime": "[16/Jan/2016:09:47:55 +0100]", 
        "epochTimeStamp": 1452934075
    },
    ...
}

Note that dateTime and epochTimeStamp are not of type $date though. You can easily create a custom transformer to fit your needs.

ujibang commented 8 years ago

regarding support for $currentDate and other field update operators I have created task https://softinstigate.atlassian.net/browse/RH-151

current master branch already contains a version that supports them on PATCH /db/coll/doc requests

ujibang commented 8 years ago

@singhvikram704

thanks for pointing out this. I added support for update operators to all resources/verbs.

this improvement will be available in next release 1.2

Basically now you can do:

PUT /db/coll/doc { a: 1, { "$currentDate": {"a": true}}, { "$push": {"array": "item"} } }
PATCH /db/coll/doc { b:2, { "$push": {"array": "item"} } }
GET /db/coll/doc
HTTP/1.1 200 OK
...

{
    "_etag": {
        "$oid": "569a62932d174c7ccf07c7e4"
    }, 
    "_id": "doc", 
    "a": {
        "$date": 1452958349130
    }, 
    "array": [
        "item", 
        "item"
    ],
   ...
}