Skip to main content

Documents And SubDocuments

GooseType provide support for mongoose's Document & Sub Document

A Document is a class:
  • Decorated with @GtDocument
  • Extends GtModel()
A Subdocument is a class:
  • Decorated with @GtSubDocument
  • Extends GtResource()
import { GtSubDocument, GtResource, GtDocument, GtModel, GtColumn } from '@pebula/goosetyped';
@GtSubDocument({ noId: true })
export class Address extends GtResource() {
@GtColumn()
street: string;
@GtColumn()
country: string;
}
@GtDocument()
export class Customer extends GtModel() {
@GtColumn()
name: string;
@GtColumn()
age: number;
@GtColumn()
address: Address;
}

Document Options (metadata)#

Most of the metadata options are straight-forward and well documented in the Api Docs.

For depp inspection check GtDocumentMetadataArgs & GtSubDocumentMetadataArgs

We will cover some of them here:

GtSubDocumentMetadataArgs.noId#

This will disable the automatic _id set for every sub document. Read more here...

caution

Since Document model must have an id, this is only valid for SubDocuments

GtDocumentMetadataArgs.connectionId#

The connection id to use when creating the model.

When not set, GooseTyped will use the default connection. When set, GooseTyped will use the registered connection to compile the model at the defined stage in the connections life.

import mongoose from 'mongoose';
import { GtDocument, GtModel, GtColumn, addConnection } from '@pebula/goosetyped';
@GtDocument({
connectionId: 'myConnection',
})
export class Customer extends GtModel() {
@GtColumn()
name: string;
@GtColumn()
age: number;
}

At this point the model class is available, but it is not connect to mongoose so no point of creating new instances of it...

const connection = mongoose.createConnection('localhost',{ /* ...*/ });
const ready = addConnection('myConnection', () => connection);
await ready;

Once ready resolves we have a guarantee that all models are compiled and bound to the connection.

note

Deffered model compilation is explained in more detail in the Async Model Compilation.