Skip to content

Commit 5af9825

Browse files
Gustavo MendonçaRomakita
authored andcommitted
feat(mongoose): Added DynamicRef decorator to support mongoose dynamic refs. Issue #567
1 parent 86b0834 commit 5af9825

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import {Property, Schema} from "@tsed/common";
2+
import {applyDecorators, Store, StoreFn, StoreMerge} from "@tsed/core";
3+
import {Schema as MongooseSchema} from "mongoose";
4+
import {MONGOOSE_SCHEMA} from "../constants";
5+
6+
/**
7+
* Define a property as mongoose reference to other Model (decorated with @Model).
8+
*
9+
* ### Example
10+
*
11+
* ```typescript
12+
*
13+
* @Model()
14+
* class FooModel {
15+
*
16+
* @DynamicRef('type')
17+
* field: Ref<OtherFooModel | OtherModel>
18+
*
19+
* @Enum(['OtherFooModel', 'OtherModel'])
20+
* type: string
21+
* }
22+
*
23+
* @Model()
24+
* class OtherFooModel {
25+
* }
26+
*
27+
* @Model()
28+
* class OtherModel {
29+
* }
30+
* ```
31+
*
32+
* @param type
33+
* @returns {Function}
34+
* @decorator
35+
* @mongoose
36+
* @property
37+
*/
38+
export function DynamicRef(refPath: string) {
39+
return applyDecorators(
40+
Property({use: String}),
41+
Schema({
42+
type: String,
43+
example: "5ce7ad3028890bd71749d477",
44+
description: "Mongoose Ref ObjectId"
45+
}),
46+
StoreFn((store: Store) => {
47+
delete store.get("schema").$ref;
48+
}),
49+
StoreMerge(MONGOOSE_SCHEMA, {
50+
type: MongooseSchema.Types.ObjectId,
51+
refPath
52+
})
53+
);
54+
}

packages/mongoose/src/decorators/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ export * from "./select";
1010
export * from "./unique";
1111
export * from "./virtualRef";
1212
export * from "./objectID";
13+
export * from "./dynamicRef";

0 commit comments

Comments
 (0)