How to populate mongoose references in nestjs?
Found it.My mistake was in defining the schema.Should be :
@Schema()export class Story extends Document { @Prop() title: string; @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' }) author: MongooseSchema.Types.ObjectId }
After much reading and testing on mongoose references in nestjs. I think the accepted answer can be improved. I will show this in 2 steps. The first step is showing the declaration of MongooseSchema and including the comment of @illnr regarding the author property to use Types.ObjectId
instead of MongooseSchema.Types.ObjectId
.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';import { Document, Types, Schema as MongooseSchema } from 'mongoose';@Schema()export class Story extends Document { @Prop() title: string; @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' }) author: Types.ObjectId }export const StorySchema = SchemaFactory.createForClass(Story);
And as a second step, I think it improves readability to use the Person class as type for the author property, as shown here.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';import { Document, Types, Schema as MongooseSchema } from 'mongoose';import { Person } from './person.schema'@Schema()export class Story extends Document { @Prop() title: string; @Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' }) author: Person}export const StorySchema = SchemaFactory.createForClass(Story);