Collection mixins Component

Options

A lot of Collection methods take an options parameter. The options available are:

OptionTypeNotes
{
Query (find*(), update(), remove())
query:MongoDB queryThe standard MongoDB-style query object.
Projection & Population (find*(), by*())
projection:MongoDB fieldsThe standard MongoDB-style fields projection that specifies the projection. Also supports extended projection syntax. This also can be called "fields", but this is deprecated.
populate:Population ProjectionThe population fields to populate.
asOf:dateIndicates that any historical documents (including populated documents) should be $asOf()'d the given date.
Windowing (find(), findAll())
limit:integerThe maximum number of documents to retrieve.
skip:integerThe number of documents to skip.
count:booleanIf set on findAll() calls then the returned documents array will have a count property indicating the total number of documents matching the query (ignoring any skip and limit). See Counting.
Sorting (find(), findAll(), byIds(), byUids())
sort:MongoDB sortThe standard MongoDB-style sort object.
Parallel Arrays (byIds(), byUids())
parallel:booleanIf true, then the returning array will be parallel to the input array of IDs/UIDs.
Caching (byIds(), byUids())
cached:booleanIf true, then the returning array will return cached values if they are present to avoid a query. (Currently only availabe in the client-side API.)
Deletions (remove())
justOne:booleanWhether to remove at most one document.
Updates - Query (update(), but NOT $update() or updateDoc())
update:MongoDB updateThe standard MongoDB-style update object. 'insert' for inserts, etc.) but you can override it with this option.
Updates - Document ($update() and updateDoc(), but NOT update())
upsert:booleanIndicates if the document should be insert()'ed if no ID field is present. (Default false.)
Historical (most saving/updating methods)
author:UID | DocumentThe author of the change that should be recorded in the historical snapshot. If author is not specified but auth is, and auth is a Document, then its UID will be used instead.
comment:stringA comment to record along with the historical update.
historical:falseNormally historical-unsafe methods log a warning if you use them with historical collections. If you set historical to false you can suppress the warning indicating that you know what you are doing. Additionally, if this flag is passed on an operation that does support historical operations, this option will suppress updating the history -- use with caution.
trueProcess history normally -- this is the default value.
'partial'If 'partial' is specified and the collection is a using the historical document format, then the smallest possible historical snapshot will be saved instead of a full snapshot (i.e. _partial will be true if not all the fields changed).
Timestamps (most saving/updating methods)
timestamps:booleanIndicates if timestamps should be updated. Defaults to the timestamps setting on the collection.
Security (most methods)
auth:Auth ObjectAn authorization object (a user, group, role, etc.) to pass to a Secure plug-in. Can also be "true" to auto-detect the current user.
perm:stringThe permission to use when an auth object is specified. Usually perm is inferred ('view' for finds, 'delete' for removes, ...)
keepNonAccessible:booleanIf present this means to not filter the documents when querying and only to call Document.$checkAccess() on the documents.
Post-processing (toClient()/$toClient())
post:opts => voidThis provides a hook to perform any post-processing on the resulting document. this is bound to the current document when this function is invoked. Note that this function is also invoked for any embedded documents as well (in this case this will be bound to the specific embedded document), so your function should be prepared to deal with potentially different types of data.
Plain 'ole JavaScript Object (POJO) conversion (find*()/by*())
plain:opts => voidThis indicates that returned documents should be raw POJO objects, not Document instances.
}

Not all options are supported by all methods. For example, findOne() uses a limit of 1 and Tyr.byUid() does not support the query option.

Population Projection

A population projection definition can take one of the following three forms:

instance

$metaType: 'collection'

This returns 'collection'.

ajax(url: string, opts: options): data

This is a method used by Tyranid internally to make its AJAX calls but which is also available as part of Tyranid's public API.

The API is essentially the same as jQuery's $.ajax() method which is currently used for the underlying implementation.

If the csrf option is enabled in Tyr.config(), then CSRF will be applied to all Tyr.ajax calls automatically.

aux(def: { [fieldName: string]: FieldDefinition }): void

This method can be used to add new auxiliary fields to an existing collection. The syntax is the same as the values provided to fields when defining a collection. For example:

User.aux({
  someClientValue: { is: 'string' }
});
byId(id: id type, opts: options): Document

This retrieves a document by its id.

byIds(ids: id type[], opts: options): Document[]

This retrieves a list of documents by their ids.

The returned array is parallel to the given ids array if the parallel option is passed as in options. If the same id shows up multiple times in the input query, then the returned array will also have multiple instances, but the instances will be shared. If a given id does not exist in the database, then the corresponding entry will still be present, but it will contain null.

byLabel(label: string): Document

This retrieves the first document it finds matching the given label using a case-insensitive search.

cache(
document: Document | object,
type: 'insert' | 'update' | 'remove',
silent: boolean = false
): Document

This method can be used to manually cache a document into the local Tyranid offline cache.

This can be useful for when a document comes back from a non-Tyranid server API call and you want to inform Tyranid about the updated document.

If Tyranid already had a local copy of the document then the existing document will be updated with the new information and the existing document will be returned.

If silent is set then local events will not be fired.

canInsert(query: MongoDB Query, perm: string, auth: authObject): MongoDB Query | boolean

If a Secure component is registered with Tyranid, this method will be used to determine if a document can be inserted into a collection relative to the authObject (usually an instance of a user document).

Most Tyranid insert and save use canInsert() internally when an auth option is used and end-users will not normally need to directly use this method.

count(opts: options): number

This returns a count of the documents that match the given opts.query.

See also Counting and also exists().

db: native MongoDB Collection

This contains a reference to the underlying native MongoDB Collection instance.

def

This defines the structure of a collection and is the argument that is passed into the Collection constructor.

All result types are automatically wrapped in a Promise. If not specified, this will return Promise.
Object StructureTypeDefaultNotes
{
id:stringrequired3 character alphanumeric code, must be unique, see UIDs.
name:stringrequired
dbName:stringname
aux:booleanfalseIf this collection is auxiliary.
server:stringdefault serverThe server to use with this collection -- see
Tyr.config({ servers: ... }).
label:stringlabelify(name)The human-readable label for this collection.
indexes:arraynoneIf present contains an array of index definitions in the format specified by the MongoDB createIndexes command
help:stringnoneContains brief user-facing documentation about this collection.
historical:'document' | 'patch'noneIndicates if this collection should have historical data support.
preserveInitialValues:Document => boolean | booleannoneThis function is invoked on a document, if it returns true then a copy of the initial values is preserved in a $orig value.
note:stringnoneContains developer-facing documentation about this collection (only visible in the Tyranid console).
enum:booleanfalseGenerates enumeration support for this collection.
static:booleanfalseGenerates static data support for this collection.
internal:booleanfalseIndicates that this is a collection used internally by Tyranid.
generated:booleanfalseIndicates that this is a collection was generated automatically.
client:booleantrueIf this is false, client-side classes for this collection will not be generated.
primaryKey: {none
field:fieldNamerequired
defaultMatchIdOnInsert:booleanfalse
},
timestamps:booleanfalseEnables timestamps on this collection.
express: {
rest:booleanfalseActivates all REST API endpoints.
get:booleanfalse
post:booleanfalse
put:booleanfalse
},
fields: {
fieldName:Field Def
...
},
methods: {Define Document methods for this collection. See Methods.
methodName: {
help:stringnoneContains brief user-facing documentation about this method.
note:stringnoneContains developer-facing documentation about this method (only visible in the Tyranid console or in IDEs).
params: {Define parameters for this method.
paramName:Field Def
},
return:Field DefDefines the return type.
fn(method parameters) { ... }functionnoneA single isomorphic function for both client and server.
fnClient(method parameters) { ... }functionnoneThe function to use on the client.
fnServer(method parameters) { ... }functionnoneThe function to use on the server.
},
...
},
values: {noneThis allows you to define static data in a tabular format.
[ '_id', 'fieldName1', ... ],The first row is a header row which contains field names.
[ id1, value1, ... ],The following rows are data rows.
...
}
projections: {
projectionName:MongoDB-style projectionDefine standard projections. See projections.
...
},
service: {Define a service for this collection.
serviceMethodName: {
help:stringnoneContains brief user-facing documentation about this service method.
note:stringnoneContains developer-facing documentation about this service method (only visible in the Tyranid console or in IDEs).
params: {Define parameters for this service method.
paramName:Field Def
},
return:Field DefDefines the return type. All result types are automatically wrapped in a Promise. If not specified, this will return Promise.
route:string/api/collection name/service method nameThis defines the HTTP route for this service. This does not usually need to be manually specified.
},
},
values: {noneThis allows you to define static data in a tabular format.
[ '_id', 'fieldName1', ... ],The first row is a header row which contains field names.
[ id1, value1, ... ],The following rows are data rows.
...
}
fromClient:async? opts => void Specifies a Collection.fromClient() post-processing hook that will be applied for this collection.

This callback can be asynchronous.

toClient:opts => voidSpecifies a Collection.toClient() post-processing hook that will be applied for this collection.

linkEvents:objectnoneDefines link event handlers recommended or required by this collection. See Event for more information.

}
exists(opts: options): boolean

This returns true if any documents that match the given opts.query (and permission checks).

See also count().

fake({ n, schemaOpts, seed } = {}): n > 1 ? Document[] : Document

This creates n fake documents (default is 1) for fields matching schemaOpts using the given seed.

fields: { field name: Field }

This is a parallel hash to def.fields that contains the generated Field objects.

fire(event: Event): void

This method fires off an event that is bound to this collection.

MyCollection.fire({ ... });

is shorthand for:

Tyr.Event.fire({ collection: MyCollection, ... });

See Event.fire() for more information.

fieldsBy(filter: Field => boolean): Field[]

This returns an array of Fields that match the given filter.

For example, following returns a list of all of the fields in the User collection that are of type string.

User.fieldsBy(field => field.def.is.def.name === 'string')
fieldsFor(opts: { match: MongoDocument | Document,
query?: MongoQuery,
custom?: boolean,
static?: boolean }): { fieldName: Field }

This is similar to def.fields except that it returns dynamic fields defined in Dynamic Schemas.

Only one of match and query should be provided.

If

If static is specified, then all statically defined fields will also be returned -- by default only dynamic fields are returned.

If custom is specified, then only dynamic fields which have custom: true set on them will be returned.

find(opts: options): Cursor<Document>

This behaves like the native MongoDB driver's find() method with the addition that results are wrapped in this collection's document type.

findAll(opts: options): Document[]

This behaves like find() except that it returns an array of Documents instead of a cursor.

findAll() also supports the count option.

findOne(opts: options): Document

This behaves like native MongoDB's findOne() method except that the results are wrapped in this collection's document type. You can also just pass in a single options object and specify the query on the options object directory.

findAndModify(opts: options)

This behaves like native MongoDB's findAndModify() method except the options are passed in a single options object and the results are wrapped in this collection's document type.

findReferences(opts): Document[]

This finds all the documents that link to the given id(s) in the database. This will also find any UID references.

OptionTypeNotes
{
id:id type | id type[]Contains an id or an array of ids to find references to.
ids:id type | id type[]Alias for "id"
idsOnly:booleanBy default the full documents are returned. If this is returned, the documents only contain their id.
exclude:Collection | Collection[]Contains a list of collections to exclude from the search.
}
fromClient(doc: object, path: string?, opts: object?): Document

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

If this collection has a fromClient hook registered it will be invoked. If Tyranid is itself calling fromClient() (for example, via automatically-generated client calls), it will pass in the express request object in the options objects available as options.req.

fromClientQuery(query: object): object

This converts a MongoDB-style query created on the client into one suitable to be used on the server. For example:

ClientServer
{
  isbn: {
    $in: [
      '5614c2f00000000000000000',
      '5614c2f00000000000000001'
    ]
  }
}
{
  isbn: {
    $in: [
      ObjectId('5614c2f00000000000000000'),
      ObjectId('5614c2f00000000000000001')
    ]
  }
}
id: string

This contains the 3-character ID for the collection.

IDs that start with _ are reserved for Tyranid collections and IDs that start with ~ are reserved for auxiliary collections.

idToLabel(id: id type): string

This returns the label for the specified id.

This method will return an empty string if it is given a non-truthy id (i.e. if the id is not defined).

idToUid(id: id type): UID string

This generates a UID from an id.

insert(doc: Document | object | Document[] | object[])

This behaves like native MongoDB's insert() method but also does things like timestamps, denormalization, and so on.

If you pass in an array, then the array of documents/objects will be inserted in bulk.

isAux(): boolean

This returns true if the collection's data is auxiliary (i.e. not presisted in the database). This is the opposite of isDb().

isDb(): boolean

This returns true if the collection's data is stored in the database. This is the opposite of isAux().

isSingleton(): boolean

This returns true if the collection is a singleton collection.

isStatic(): boolean

This returns true if the collection's data is defined statically in its def.values field. Enumerations are a common example of static collections.

isUid(uid: UID string): boolean

This returns true if the given UID refers to a document in this collection.

label: string

This returns a label, or display name, for the collection itself.

labelField: Field

If this collection has a field that is marked with labelField this returns the that field.

labelFor(doc: Document | object): string

This returns the label for the specified document. If doc is a Document, then this is equivalent to doc.$label. This method is mostly useful for when you have a raw object that you want to get the label for.

labels(text: string): { _id: id type, label field: string }[]
labels(ids: string[]): { _id: id type, label field: string }[]

This generates a list of label objects that can be used to populate a typeahead dropdown.

Generally prefer to use Field.labels() over this as it can take advantage of the where property on link fields.

migratePatchToDocument(progress?: (count: number) => void): void

This function will migrate a collection with patch-format historical data to one with document-format historical data.

The progress parameter is a callback that will be called periodically with the number of documents that have been converted. For example:

Widget.migratePatchToDocument(count => console.log(`converted ${count} documents`))
mixin(def: def Object): void

This allows you to mixin additional metadata (like additional fields) to an existing collection. This is useful for adding additional metadata to built-in Tyranid or third-party collections. See Mixins for more information.

on(opts: object): () => void

Lets you add an event handler on this collection. See on() for more information on this method.

parsePath(text: string): Path

This parses a path into a Path object.

See also Document.parsePath.

paths: { field path name: Field }

This is a hash of all the fields inside a collection by their path names. Paths are often more convenient to work with than recursively walking the def.fields.* structure.

Note that unlike Collection.fields which just has the top-level fields, paths contains nested fields as well.

populate(projection: Population Projection, documents: Document | Document[], denormal: boolean)

If documents is not provided, this function will return a curried version of this function that takes a single array of documents. This allows populate to be fed into a promise chain.

See Population for more information and examples.

pull(id: id type, path: string, predicate: any => boolean, opts: options?)

This method assumes that path points to an array inside the document. This method will remove all elements of the array that match the predicate function.

For example:

User.pull(myId, 'name.suffices', suffix => suffix === 'Sr');

This method will also retain historical information for historical documents.

push(id: id type, path: string, value: any, opts: options?)

This is a shortcut for:

collection.update({ _id: id }, { $push: { [path]: value } })

However, this method will also atomically retain historical information for historical documents.

remove(id: id type | query: object, justOne: boolean?)

This behaves like native MongoDB's remove() method.

removeReferences(opts): void

This finds all references in documents that link to the given id(s) in the database and removes them. This will also remove any UID references.

OptionTypeNotes
{
id:id type | id type[]Contains an id or an array of ids to remove references to.
ids:id type | id type[]Alias for "id"
exclude:Collection | Collection[]Contains a list of collections to exclude from the removal.
}
save(doc: Document | object | Document[] | object[]): Document

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

When updating, the entire document is replaced. Use updateDoc() to only modify updated fields.

secureQuery(query: MongoDB Query, perm: string, auth: authObject): MongoDB Query | boolean

If a Secure component is registered with Tyranid, this method will update the query with security restrictions the secure component mandates relative to the authObject (usually an instance of a user document).

Warning: This method will return false if the query is categorically rejected so it is important that the results of this are not immediately passed into a subsequent query. You need to look at the result and if it is false short-circuit the query. See secureFindQuery().

Most Tyranid methods use secureQuery internally when an auth option is used and end-users will not normally need to directly use this method.

secureFindQuery(query: MongoDB Query, perm: string, auth: authObject): MongoDB Query

This method behaves like secureQuery() except that this method will not ever return a boolean. If the security component detects that a query is categorically rejected, this method will return a valid MongoDB query object that is guaranteed to fail-fast (something like { _id: null }).

subscribe(query: MongoDB Query, cancel?: boolean): void

This subscribes the current client to the given query. When changes that match the given query are made the client objects will be updated automatically on the client with the changes.

If the cancel parameter is passed in as true, then the given subscription will be canceled.

If cancel is true and query is undefined, then all subscriptions will be canceled.

toClient(doc: Document, opts: object?): object

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

opts can contain the following:

OptionTypeNotes
{
auth:Auth ObjectAn authorization object (a user, group, role, etc.). This value is also accessible to hook functions like Collection.def.toClient and post below.
fields:MongoDB fieldsThe standard MongoDB-style fields object that specifies the projection. Also supports extended projection syntax. Any field not in this projection will not be copied to the resulting toClient() object.
post:opts => voidThis provides a hook to perform any post-processing on the resulting document. this is bound to the current document when this function is invoked. Note that this function is also invoked for any embedded documents as well (in this case this will be bound to the specific embedded document), so your function should be prepared to deal with potentially different types of data.
}

Any toClient function defined for a collection in its Collection.def will also be invoked during toClient processing. This provides a standard place where fields can be removed for security and other reasons. As with post(), this is bound to the current document inside a collection's toClient() post-processing function.

$toClient() will also invoke the Document.$redact() method on documents.

update(query: object, update: object, opts: options)

This behaves like native MongoDB's update() method. It also will update timestamps if this collection is configured to use them.

updateDoc(doc: Document | object, opts: options): Document

This updates the server document with the values in this object.

Note that the document is not replaced. See Collection.save() if you want to do a full replace.

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.

values: Document[]

This contains a list of all documents that are cached locally on a client for off-line use.

valuesFor(fields: Field[]): any[]

This method returns all of the unique values that appear for the given fields in the collection.