Skip to main content

Ref<PopulatedType, RawId>

Typings:

type Ref<
PopulatedType,
RawId extends mongoose.RefType = PopulatedType extends { _id?: mongoose.RefType }
? NonNullable<PopulatedType['_id']>
: mongoose.Types.ObjectId
>

Parameters:

NameTypeDescription
PopulatedType RequiredobjectThe Type of the what is expected when it is populated
RawIdmongoose.RefTypeOverwrite the Reference type (the type of _id of PopulatedType)

The Type Ref<PopulatedType, RawId> is the type used for References.

  • PopulatedType: This is the Class being referenced.
  • RawId: This should be the _id Type of the referenced Class, by default its mongoose.Types.ObjectId and should get automatically inferred if a _id property is present on the target class.

There are typeguards to check if a reference is populated or of the reference type:

tip

For more and better explained examples, look at the Reference Other Classes Guide.

Example

Class to-be-referenced:

class Kitten {
@prop()
public name?: string;
}

Single Reference:

class Person {
@prop({ ref: () => Kitten })
public pet?: Ref<Kitten>;
}

Reference Array:

class Cat {
@prop({ ref: () => Kitten })
public babies?: Ref<Kitten>[];
}

Reference with different _id type:

class Kitten {
@prop()
public _id?: string;

@prop()
public name?: string;
}

// For Single References
class Person {
// The "type" options in this case refers to the "_id" type of the referenced class, by default it will be "ObjectId"
@prop({ ref: () => Kitten, type: () => String })
public pet?: Ref<Kitten, string>;
}

// For a Array of References
class Person {
// The "type" options in this case refers to the "_id" type of the referenced class, by default it will be "ObjectId"
@prop({ ref: () => Kitten, type: () => String })
public pet?: Ref<Kitten, string>[];
}