4

I have checked the documentation of how to do this, but I have not found an answer.

Basically, when a document is created/published, I want to set a createdDate for the document (as a read-only/hidden field).

thomax
  • 9,213
  • 3
  • 49
  • 68
JAM
  • 6,045
  • 1
  • 32
  • 48

2 Answers2

7

I found the answer here.

At its core, a document is a JSON-object that has a unique _id, timestamps (_createdAt, _updatedAt) and revision-marker _rev.

So the created date is generated automatically by sanity, including many other interesting properties.

JAM
  • 6,045
  • 1
  • 32
  • 48
  • 4
    Exactly. _createdAt is a read-only property locked in when the document is created. You can actually submit a _createdAt and _updatedAt value as the document is created (via the apis, in order to support importing data recreating their history), but after creation, the fields are read-only and are managed entirely by Sanity. – svale Mar 01 '18 at 10:36
1

As mentioned in svale's comment, it is possible to set both _createdAt and _updatedAt but only upon creation. I've been using Sanity's official JS client and it allows me to do this:

await client.create({
    _type: "someType",
    _createdAt: "2019-12-31T12:34:56Z",
    _updatedAt: "2020-01-01T12:34:56Z",
});

Additionally, it's possible to set a custom _id if needed.

When updating a document, those attributes are indeed read-only and cannot be manually changed.

Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62