Property

Default usage

Below is the simplest property definition.

@Definition()
export class Tag {
  @Property()
  name: string;
}

It is equivalent to:

  • @Prop() or @Prop({ type: String }) with @nest/mongoose.
  • @Field() or @Field(() => graphql.GraphQLString) with @nestjs/graphql.
💡

By default, name is required on CreateInputType and OutputType but is nullable on UpdateInputType.

Custom GraphQL type

Override inferred type

We can specify a custom GraphQL type.

@Definition()
export class Product {
  @Property({ type: () => graphql.GraphQLInt })
  saleCount: number;
}

Different GraphQL types for each purpose

We can have different types with different options for CreateInputType, UpdateInputType and OutputType.

The options on top level will be the default options for all types, and the options on create, update and output will override the default options for the corresponding type.

@Definition()
export class Product {
  @Id()
  id: ObjectId;
 
  @Property({
    type: () => graphql.GraphQLInt,
    create: { defaultValue: 0 },
    output: { nullable: true, type: () => graphql.GraphQLFloat },
    update: Skip,
  })
  saleCount: number;
}
💡

Skip is imported from 'dryerjs', if you put Skip on create update or output the property will not be generated for the corresponding type.

Custom Mongoose type

By giving db field on @Property we can specify a custom Mongoose type and its options.

@Definition()
export class User {
  @Property({ db: { unique: true } })
  email: string;
 
  @Property({ db: { type: Date } })
  createdAt: Date;
}
💡

You can also skip the db field by giving db: Skip so that it will ignored by the database.