Skip to content

Commit 8fa9a3d

Browse files
Merge branch 'patch-5' of github.com:getTobiasNielsen/docs.nestjs.com into getTobiasNielsen-patch-5
2 parents 3937a94 + 2f3774f commit 8fa9a3d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

content/techniques/mongo.md

+21
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,27 @@ In case there are multiple owners, your property configuration should look as fo
8989
owners: Owner[];
9090
```
9191

92+
If you do not plan on always populating a reference to another collection, you should consider using `mongoose.Types.ObjectId` as the type instead:
93+
94+
```typescript
95+
@Prop({ type: { type: mongoose.Schema.Types.ObjectId, ref: 'Owner' } })
96+
// This is crucial to not confuse the field with a populated reference
97+
owner: mongoose.Types.ObjectId;
98+
```
99+
100+
Then when you want to selectively populate it later, you can make use of a repository function that specifies the correct type:
101+
102+
```typescript
103+
import { Owner } from './schemas/owner.schema';
104+
105+
// e.g. inside a service or repository
106+
async findAllPopulated() {
107+
return this.catModel.find().populate<{ owner: Owner }>("owner");
108+
}
109+
```
110+
111+
> info **Hint** If there is no foreign document to populate, the type might be `Owner | null` depending on your (mongoose configuration)[https://mongoosejs.com/docs/populate.html#doc-not-found], or it might throw, in which case the type will be `Owner`.
112+
92113
Finally, the **raw** schema definition can also be passed to the decorator. This is useful when, for example, a property represents a nested object which is not defined as a class. For this, use the `raw()` function from the `@nestjs/mongoose` package, as follows:
93114

94115
```typescript

0 commit comments

Comments
 (0)