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).

2 Answers 2

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.

1
  • 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 1, 2018 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.