1
- import { Schema , model , Document , Types , Query , Model , QueryWithHelpers } from 'mongoose' ;
1
+ import { Schema , model , Document , Types , Query , Model , QueryWithHelpers , PopulatedDoc } from 'mongoose' ;
2
+ import { ObjectId } from 'mongodb' ;
2
3
3
4
interface QueryHelpers {
4
5
_byName ( this : QueryWithHelpers < any , ITest , QueryHelpers > , name : string ) : QueryWithHelpers < Array < ITest > , ITest , QueryHelpers > ;
5
6
byName ( name : string ) : QueryWithHelpers < Array < ITest > , ITest , QueryHelpers > ;
6
7
}
7
8
9
+ const childSchema : Schema = new Schema ( { name : String } ) ;
10
+ const ChildModel = model < Child > ( 'Child' , childSchema ) ;
11
+
8
12
const schema : Schema < ITest , Model < ITest , QueryHelpers > > = new Schema ( {
9
13
name : { type : 'String' } ,
10
14
tags : [ String ] ,
15
+ child : { type : 'ObjectId' , ref : 'Child' } ,
11
16
docs : [ { _id : 'ObjectId' , id : Number , tags : [ String ] } ] ,
12
17
endDate : Date
13
18
} ) ;
@@ -21,6 +26,9 @@ schema.query.byName = function(name: string): QueryWithHelpers<any, ITest> {
21
26
return this . _byName ( name ) ;
22
27
} ;
23
28
29
+ interface Child {
30
+ name : string ;
31
+ }
24
32
interface ISubdoc extends Document {
25
33
myId ?: Types . ObjectId ;
26
34
id ?: number ;
@@ -31,13 +39,16 @@ interface ITest extends Document {
31
39
name ?: string ;
32
40
age ?: number ;
33
41
parent ?: Types . ObjectId ;
42
+ child ?: PopulatedDoc < Child & Document < ObjectId > > ,
34
43
tags ?: string [ ] ;
35
44
docs ?: ISubdoc [ ] ;
36
45
endDate ?: Date ;
37
46
}
38
47
39
48
const Test = model < ITest , Model < ITest , QueryHelpers > > ( 'Test' , schema ) ;
40
49
50
+ Test . find ( { } , { } , { populate :{ path :"child" , model :ChildModel , match :true } } ) . exec ( ) . then ( ( res : Array < ITest > ) => console . log ( res ) )
51
+
41
52
Test . find ( ) . byName ( 'test' ) . byName ( 'test2' ) . orFail ( ) . exec ( ) . then ( console . log ) ;
42
53
43
54
Test . count ( { name : / T e s t / } ) . exec ( ) . then ( ( res : number ) => console . log ( res ) ) ;
0 commit comments