0
# Schema Definition
1
2
Decorators and utilities for defining MongoDB schemas using TypeScript classes with full type safety. The schema definition system allows declarative schema creation using class-based decorators.
3
4
## Capabilities
5
6
### @Schema Decorator
7
8
Marks a TypeScript class as a Mongoose schema definition.
9
10
```typescript { .api }
11
/**
12
* Class decorator that marks a TypeScript class as a Mongoose schema
13
* @param options - Mongoose schema options
14
* @returns Class decorator function
15
*/
16
function Schema(options?: SchemaOptions): ClassDecorator;
17
18
type SchemaOptions = mongoose.SchemaOptions;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { Schema, Prop } from '@nestjs/mongoose';
25
26
// Basic schema
27
@Schema()
28
export class User {
29
@Prop({ required: true })
30
name: string;
31
32
@Prop()
33
email: string;
34
}
35
36
// Schema with options
37
@Schema({
38
timestamps: true,
39
collection: 'users',
40
versionKey: false,
41
})
42
export class User {
43
@Prop({ required: true, index: true })
44
username: string;
45
46
@Prop({ select: false })
47
password: string;
48
49
createdAt: Date;
50
updatedAt: Date;
51
}
52
```
53
54
### @Prop Decorator
55
56
Marks a class property as a Mongoose schema property with type and validation options.
57
58
```typescript { .api }
59
/**
60
* Property decorator that defines a Mongoose schema property
61
* @param options - Property definition options
62
* @returns Property decorator function
63
*/
64
function Prop(options?: PropOptions): PropertyDecorator;
65
66
type PropOptions = Partial<mongoose.SchemaDefinitionProperty> | mongoose.SchemaType;
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { Schema, Prop } from '@nestjs/mongoose';
73
import { Types } from 'mongoose';
74
75
@Schema()
76
export class Product {
77
// Basic property
78
@Prop()
79
name: string;
80
81
// Required property with validation
82
@Prop({ required: true, min: 0 })
83
price: number;
84
85
// Property with default value
86
@Prop({ default: Date.now })
87
createdAt: Date;
88
89
// Array property
90
@Prop([String])
91
tags: string[];
92
93
// Object reference
94
@Prop({ type: Types.ObjectId, ref: 'User' })
95
owner: Types.ObjectId;
96
97
// Nested object
98
@Prop({
99
type: {
100
street: String,
101
city: String,
102
zipCode: String,
103
}
104
})
105
address: {
106
street: string;
107
city: string;
108
zipCode: string;
109
};
110
111
// Enum property
112
@Prop({ enum: ['active', 'inactive', 'pending'] })
113
status: string;
114
115
// Property with custom validation
116
@Prop({
117
validate: {
118
validator: (v: string) => v.length >= 3,
119
message: 'Name must be at least 3 characters long'
120
}
121
})
122
displayName: string;
123
}
124
```
125
126
### @Virtual Decorator
127
128
Marks a property as a Mongoose virtual property that is computed dynamically.
129
130
```typescript { .api }
131
/**
132
* Property decorator that defines a Mongoose virtual property
133
* @param options - Virtual property options
134
* @returns Property decorator function
135
*/
136
function Virtual(options?: VirtualOptions): PropertyDecorator;
137
138
interface VirtualOptions {
139
/** Virtual type options */
140
options?: any; // VirtualTypeOptions from mongoose
141
/** Sub-path for nested virtuals */
142
subPath?: string;
143
/** Getter function for the virtual property */
144
get?: (...args: any[]) => any;
145
/** Setter function for the virtual property */
146
set?: (...args: any[]) => any;
147
}
148
```
149
150
**Usage Examples:**
151
152
```typescript
153
import { Schema, Prop, Virtual } from '@nestjs/mongoose';
154
155
@Schema()
156
export class User {
157
@Prop({ required: true })
158
firstName: string;
159
160
@Prop({ required: true })
161
lastName: string;
162
163
@Prop()
164
email: string;
165
166
// Simple virtual property
167
@Virtual()
168
get fullName(): string {
169
return `${this.firstName} ${this.lastName}`;
170
}
171
172
// Virtual with getter and setter
173
@Virtual({
174
get: function() {
175
return this.email?.split('@')[0];
176
},
177
set: function(username: string) {
178
this.email = `${username}@example.com`;
179
}
180
})
181
username: string;
182
183
// Virtual populate
184
@Virtual({
185
options: {
186
ref: 'Post',
187
localField: '_id',
188
foreignField: 'author',
189
}
190
})
191
posts: any[];
192
}
193
```
194
195
## Advanced Schema Features
196
197
### Raw Object Definition
198
199
For complex nested objects that should bypass type transformation:
200
201
```typescript
202
import { raw } from '@nestjs/mongoose';
203
204
@Schema()
205
export class Analytics {
206
@Prop(raw({
207
impressions: { type: Number, default: 0 },
208
clicks: { type: Number, default: 0 },
209
conversions: { type: Number, default: 0 },
210
metadata: mongoose.Schema.Types.Mixed
211
}))
212
stats: Record<string, any>;
213
}
214
```
215
216
### Discriminator Schemas
217
218
For inheritance-based schema patterns:
219
220
```typescript
221
@Schema()
222
export class Animal {
223
@Prop({ required: true })
224
name: string;
225
226
@Prop({ required: true })
227
species: string;
228
}
229
230
@Schema()
231
export class Dog extends Animal {
232
@Prop()
233
breed: string;
234
235
@Prop()
236
isGoodBoy: boolean;
237
}
238
239
@Schema()
240
export class Cat extends Animal {
241
@Prop()
242
livesRemaining: number;
243
}
244
```
245
246
### Schema with Indexes
247
248
```typescript
249
@Schema({
250
indexes: [
251
{ name: 1 },
252
{ email: 1, username: 1 },
253
{ createdAt: -1 },
254
{ location: '2dsphere' }
255
]
256
})
257
export class User {
258
@Prop({ required: true, index: true })
259
name: string;
260
261
@Prop({ unique: true })
262
email: string;
263
264
@Prop({ index: true })
265
username: string;
266
267
@Prop({ index: '2dsphere' })
268
location: {
269
type: string;
270
coordinates: number[];
271
};
272
}
273
```
274
275
## Type Definitions
276
277
### Property Metadata Interfaces
278
279
Internal interfaces used by the metadata storage system:
280
281
```typescript { .api }
282
interface PropertyMetadata {
283
target: Function;
284
propertyKey: string;
285
options: PropOptions;
286
}
287
288
interface SchemaMetadata {
289
target: Function;
290
options?: SchemaOptions;
291
}
292
293
interface VirtualMetadataInterface {
294
target: Function;
295
propertyKey: string;
296
options?: VirtualOptions;
297
}
298
```