Hi! How to add a doc via sanity client that has a *weak* reference? If I do this, it throws an error `key "weak" not allowed in ref`: ```const author = { _type: 'reference', ...

1 replies
Last updated: Feb 2, 2021
Hi! How to add a doc via sanity client that has a weak reference? If I do this, it throws an error `key "weak" not allowed in ref`:
const author = {
  _type: 'reference',
  _ref: id,
  weak: true,
};
However, if I remove
weak
, after creating the doc via sanity client the studio tells me "Warning: This reference is strong, but should be weak according to schema."
AI Update

Perfect! I found the answer. The issue is with the property name when creating documents programmatically.

When defining a weak reference in your schema, you use weak: true, but when creating or updating documents through the Sanity client (via mutations), you need to use _weak: true (with an underscore) instead:

const author = {
  _type: 'reference',
  _ref: id,
  _weak: true,  // Note the underscore!
};

This is a naming convention difference between schema definitions and the actual document format. The weak references documentation specifically covers this distinction.

So your corrected code should look like:

// When creating via Sanity client
const doc = {
  _type: 'myDocument',
  author: {
    _type: 'reference',
    _ref: id,
    _weak: true  // Use _weak, not weak
  }
};

client.create(doc);

The _weak property tells Sanity that this reference doesn't require the referenced document to exist and allows it to point to draft documents. This is particularly useful when referencing documents that are still in draft mode or when you need more flexible content workflows where documents can be created in any order.

Try
_weak
instead, with the underscore πŸ™‚ Without it only goes for schemas, not the actual JSON. Sorry about the confusion there.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?