Documents are instances of Collections.

Document fields usually start with a "$" so that the Tyranid fields do not conflict with the underlying data being modeled.
$: TaggedTemplateLiteral => any

This is a short-cut for $get() using tagged template literals.

For example:


is equivalent to:

$access: AccessResult

This contains the result of a $checkAccess() call.

$asOf(date, fields: object?): void

This rolls back the object in-place to the given date if its collection supports historical data.

date can be either an instance of Date or the number of UTC milliseconds (Date.getTime()).

Note that once a document is rolled back to an earlier date the document is essentially read-only as updating it in the past does not make sense. Tyranid will mark the document as $historical which will prevent calls like $save from being used on it.

If the fields object is present, it indicates that only changes for the listed properties should be applied (by default all properties are patched). For example:

Note that if using patch historical storage, then this method is not asynchronous.

const fields = { name: 1, age: 1 };
const myUser = User.byId(myId, { fields });
doc.$asOf(new Date(...), fields);

Be sure to include the _history in your projection on any object you plan to use $asOf() on.

$cache(): this

This updates the local client-side database cache with the contents of this document.

$checkAccess(opts: Options): MongoDB query object

opts should contain a perm and auth option otherwise this method is likely a no-op (depending on how the Secure is written).

If a Secure component is registered with Tyranid, Tyranid will invoke its checkAccess() method to populate the $access object on this document.

Use $redact() to process the $access object and remove fields that users do not have access to. $redact() is separate from $checkAccess so that server methods can access hidden properties to create computed visible data.

$checkAccess() is invoked automatically by find*() and byId* methods automatically if an auth is passed in. Furthermore, toClient methods also automatically invoke $redact(). So you usually do not need to manually invoke either method.

$clone(): Document

This performs a shallow in-memory clone of the current document that also retains the class into the cloned document.

See also $cloneDeep().

$cloneDeep(): Document

This performs a deep in-memory clone of the current document that also retains the class into the cloned document.

See also $clone().

$copy(obj, keys: (string[] | Tyr.$all)?): void

This copies values from obj into the current object. If the target object has historical properties like _history or $orig these will not be copied.

If the keys parameter is:

$get(path: string): any

This method returns a value from the current object according to the given path.

This is shorthand for:

return this.$model.parsePath(path).get(this);

This method is analogous to Lodash's _.get().

Because this method uses Path to parse the data, it will also deal with embedded arrays and populated/denormalized values. For example, if organization is a link, then:


is equivalent to


Like Lodash's _.get, $get() handles the case where organization$ is undefined.

A tagged template literal short-cut for this method is available as $.

$historical: boolean

This indicates that this is a read-only document that is a historical version of another document created using $asOf.

_history: snapshot[]

If historical data is enabled for this collection, then this field will contain an array of historical snapshots for this document.

The format of each snapshot document is:

Object StructureNoteTypeNotes
a:AuthorUIDA UID referencing the author of the change.
c:CommentStringAn optional comment about the change.
o:OnDate in UTC msThe date this snapshot was taken (from Date.getTime()).
p:PatchpatchThe patch object containing the differences.

Users of Tyranid do not usually need to work with this history property directly.

Also, if you are using historical data, do not have a field named "history" as Tyranid will overwrite it with this array.

$id: id type

This returns the id for this document. This is usually (but not always) the contents of _id.

$insert(options: Options?): Document
$isNew: boolean

This returns true if this is a new document that has not been saved to the database yet.

$label: string

This returns the label for this document. See labels.

$metaType: 'document'

This returns 'document'.

$model: Collection

This is a reference to the collection of this document. this.$model is equivalent to this.constructor.

$options: object

This read-only property contains a reference to the Options instance that was used to find this object.

$orig: object

This will contain all of the original values for the document if historical data is enabled for this collection or if the preserveInitialValues property is set for the collection.

This property is also available on the client if $snapshot() has been called.

$parsePath(path: string): Path

This is equivalent to Collection.parsePath() except that it also finds dynamic schema paths using the current document as match criteria.

$populate(fields, denormal: boolean): this

This is equivalent to doc.$model.populate(fields, doc, denormal).

Also see Population for more information and examples.

$redact(): void

If an $access property is present on this document, $redact() will process that object and remove fields that the end-user does not have access to.

$redact is called automatically by $toClient() and Collection.toClient().

$remove(options: Options?): void

This removes the current document from the database.

$replace(obj): void

This is a short-cut for $copy(obj, Tyr.$all).

$revert(): void

If an object has an $orig property available then this method will revert the contents of this document to those values.

$save(options: Options?): Document

This method will either update or insert the object based on whether it has an _id.

When updating, the entire object is replaced. See $update() to only update instead of replace.

If the document ends up being inserted, the document returned by this method will have its _id set.

This method will use $options() as a default set of options.

$set(path: string, value: any): any

This method sets a value on the current object according to the given path.

This is shorthand for:

return this.$model.parsePath(path).set(this, value, { create: true });

This method is analogous to Lodash's _.set().

$slice(path, options): void

This reads in a slice of values into an embedded array. This can be useful if a document contains large arrays and you want to read in the array values separately and/or page them down to the client.

options are:

limit:integerHow many elements to slice.
where:any => booleanA predicate function that can be used to filter the array. Is applied before skip/limit.
populate:population objectA population object.
skip:integerWhere to start slicing the array.
sort:MongoDB-style sort objectSpecifies how to sort the array. Is applied before skip/limit.

The array values are stored in the local object's array at the given skip and offset positions in the given sort order. For this reason, do not call $slice() multiple times with different sort values.


const myDoc = Tyr.byId(myKey, { fields: { hugeArray: 0 } });
myDoc.$slice('hugeArray', {
  where: v => v.myActiveField,
  population: { myLinkPropInHugeArray: $all, myOtherPropInHugeArray: 1 },
  skip: 10,
  limit: 10,
  sort: { myField: -1, myOtherField: 1 }
$snapshot(updateHistory: boolean, options: Options?): snapshot

This historical data method compares the $orig property and the current state of the object and returns a snapshot record.

If updateHistory is true, the _history property is expected to be present it will be updated in memory. Otherwise you are expected to insert the snapshot returned into the _history property yourself.

After the snapshot is taken, the object's current $orig property is updated to the current values of the object (so you can make more changes and then do another $snapshot().

Historical options like author and comment are supported.

This method does not update the database.

This method can be useful if you want to make a number of snapshots in memory and write them out at once (bulk updates for many documents, single updates when importing history from another source, and so on).

This method is also available in the client-side API but the client-side API does not take any arguments.

$toClient(opts: object?): object

This creates a new POJO out of this document. Values are copied by reference (not deep-cloned!).

This method passes through to Collection.toClient(), so see that method for a description of opts and a more detailed explanation of how this method works.

$toPlain(): object

This creates a new Plain 'ole JavaScript Object (POJO) out of this document. Values are copied by reference (not deep-cloned!).

Unlike $toClient(), client processing is not performed. This version is also available on the client.

$tyr: Tyr

This is a reference to the tyranid namespace object Tyr.

This property can be essential if you are writing isomorphic properties or methods inside tyranid since this value will not be name-mangled. For example, if your code is being uglified (or some equivalent), then in a production build the "Tyr" inside the getter will get name mangled:

... = new Tyr.Collection({
  fields: {
    myPredicateProperty: {
      is: 'boolean',
      get() { return this.myStatus === Tyr.byName.myEnum.MY_VALUE._id; }

The following getter will be fine even under name-mangling:

... = new Tyr.Collection({
  fields: {
    myPredicateProperty: {
      is: 'boolean',
      get() { return this.myStatus === this.$tyr.byName.myEnum.MY_VALUE._id; }
$uid: string

This returns the UID for this document.

$update(options: Options?): Document

This updates the server document with the values in this object. Note that the document is not replaced. See $save() if you want to do a full replace.

This method is a short-cut for Collection.updateDoc().

If the document is new (it does not have an _id) then an exception will be thrown unless the upsert option is set to true.

This method will use $options() as a default set of options.

$validate(): UserError[]

This validates the current document according to the validation rules specified by the metadata for this collection.