Skip to content

Definition of Model

Markus Gilg edited this page Oct 21, 2018 · 7 revisions

Specifying a Collection

A collection can always be only one class or an inherited class. To do this, the class must be provided with an @collection decorator.

@collection({
  allow: 'CUD'
})
export class User {
  @validation({type:BaseTypes.mongoDbObjectId.default(null)})
  _id: string;
  @validation({type:BaseTypes.stringDefaultLength})
  firstName: string;
  @validation({type:BaseTypes.stringDefaultLength})
  lastName: string;
  @validation({type:BaseTypes.email})
  email: string;
  accounts: BankAccount[];
}

allow

The least the @collection decorator needs is permissions. This is done via the allow property. This is a string and indicates whether an object can be created, updated or deleted. The following combinations are possible:

  • CUD => All 3 operations are possible
  • XUD => No new objects can be created but existing objects can be update/deleted.
  • XXD => Only objects can be deleted
  • XXX => The Collection is read-only
  • CUX => Only objects can be created/updated.
  • CXX => Only objects can be created

Connecting multiple objects

Several objects can be linked together. Each object is stored in its own collection and linked with the $lookup function of Mongodb. For this the MongoLookup class is used in which 4 parameters are specified.

  • from => Collection in which the other objects are located.
  • localField => Propertyname of the object in which the other objects are located.
  • foreignField => Propertyname of the other object to which you want to link.
  • JoinType => relationship type

There are 2 different types of links, one to one and one to many. These two link types can be selected using the Enumeration JoinType.

User Model:

@collection({
  allow: 'CUD',
  lookup: [
    new MongoLookup('BankAccount', 'accounts', '_id', JoinType.ONEMANY)
  ]
})
export class User {
  @validation({type:BaseTypes.mongoDbObjectId.default(null)})
  _id: string;
  @validation({type:BaseTypes.stringDefaultLength})
  firstName: string;
  @validation({type:BaseTypes.stringDefaultLength})
  lastName: string;
  @validation({type:BaseTypes.email})
  email: string;
  accounts: BankAccount[];
}

BankAccount Model:

@collection({
  allow: 'CUD',
  lookup: [
    new MongoLookup('User', 'owner', '_id', JoinType.ONEONE)
  ]
})
export class BankAccount {
  @validation({type:BaseTypes.mongoDbObjectId})
  _id?: string;
  @validation({type:BaseTypes.stringDefaultLength})
  accountNumber: string;
  @validation({type:BaseTypes.stringDefaultLength})
  title: string;
  owner: User;
}

Back to Index