Reference

Relations between documents are modeled using the reference type. To model a one-to-many relation, store the references in an array.

References can be either strong (default) or weak. A strong reference will enforce that the document it points to actually exists, and will not allow deletion of a document that any other document refers to. A weak reference allows pointing to documents that may not exist (yet) or may have been deleted.

Gotcha

Whether a reference should be strong or weak is configured by setting the weak property on the reference field. Note that merely changing this property won't automatically update reference fields in the data store.

Properties

  • REQUIREDtypestring

    Value must be set to reference.

  • toarray

    Required. Must contain an array naming all the types which may be referenced e.g. [{type: 'person'}]. See more examples below.

  • weakboolean

    Default false. If set to true the reference will be made weak. This means you can discard the object being referred to without first deleting the reference, thereby leaving a dangling pointer.

Validation

  • required()function

    Ensures that this field exists.

  • custom(fn)function

    Creates a custom validation rule.

Example: Default reference

Define the movie's director as a reference to a person:

Input

{
  name: 'movie',
  type: 'object',
  fields: [
    {
      title: 'Director',
      name: 'director',
      type: 'reference',
      to: [{type: 'person'}]
    }
  ]
}

Output

{
  "_type": "reference",
  "_ref": "ffda9bed-b959-4100-abeb-9f1e241e9445" /* This could be the id of Jessica Chastain */
}

Example: Weak reference

Define the screening's movie as a weak reference to a movie, thereby allowing the movie to be deleted without deleting the screening first:

Input

{
  name: 'screening',
  type: 'document',
  fields: [
    {
      name: 'movie',
      title: 'Movie',
      type: 'reference',
      weak: true,
      to: [{type: 'movie'}],
      description: 'Which movie are we screening'
    },
  ]
}

Output

{
  "_type": "reference",
  "_ref": "93f3af18-337a-4df7-a8de-fbaa6609fd0a" /* Movie id */
  "_weak": true
}

Example: Allow reference to more than one type

The directors field is an array which can contain both person and bovinae (in the rare occasion a cow would direct a movie) references:

Input

{
  title: 'Directors',
  name: 'directors',
  type: 'array',
  of: [
    {
      type: 'reference',
      to: [
        {type: 'person'},
        {type: 'bovinae'}
      ]
    }
  ]
}

Output

[
  {
    "_type": "reference",
    "_ref": "9b711031-3744-47ab-9bb7-1bceb177d0d0" /* this could be the id of a Yvonne, the escaped cow */
  },
  {
    "_type": "reference",
    "_ref": "ffda9bed-b959-4100-abeb-9f1e241e9445" /* this could be the id of Matt Damon */
  }
]