15

I define a Person and Story schemas :

    @Schema()
    export class Person extends Document {
      @Prop()
      name: string;
    }
    export const PersonSchema = SchemaFactory.createForClass(Person);
    
    
    @Schema()
    export class Story extends Document {
    
      @Prop()
      title: string;
    
      @Prop()
      author:  { type: MongooseSchema.Types.ObjectId , ref: 'Person' }
    
    }
    export const StorySchema = SchemaFactory.createForClass(Story);

In my service I implemented save and read functions:

        async saveStory(){
        const newPerson = new this.personModel();
        newPerson.name  = 'Ian Fleming';
        await newPerson.save();
        const newStory  = new this.storyModel();
        newStory.title = 'Casino Royale';
        newStory.author = newPerson._id;
        await newStory.save();
      }
    
      async readStory(){
        const stories = await this.storyModel.
            findOne({ title: 'Casino Royale' })
        console.log('stories ',stories);
      }

When I ran readStory() I get the following output:

     stories  {
      _id: 5f135150e46fa5256a3a1339,
      title: 'Casino Royale',
      author: 5f135150e46fa5256a3a1338,
      __v: 0
    }

When I add a populate('author') to my query then I get author as null:

     stories  {
      _id: 5f135150e46fa5256a3a1339,
      title: 'Casino Royale',
      author: null,
      __v: 0
    }

How do I populate the author field with the referenced Person document ?

Antoni
  • 1,316
  • 2
  • 16
  • 42
Yaron
  • 1,655
  • 6
  • 20
  • 38

3 Answers3

16

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);
Antoni
  • 1,316
  • 2
  • 16
  • 42
Dick Bos
  • 384
  • 3
  • 8
8

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  
}
Antoni
  • 1,316
  • 2
  • 16
  • 42
Yaron
  • 1,655
  • 6
  • 20
  • 38
  • 2
    Thank you! Setting the type in the `Prop` options was the solution to my problem, since I am using union types for actual typescript typings. Btw: you can also `import { Types } from 'mongoose';` and then use `author: Types.ObjectId`. – illnr Oct 12 '20 at 08:44
  • How would you write this for an array? I tried wrapping in an array like this: @Prop([{ type: MongooseSchema.Types.ObjectId , ref: 'Person' }]) – austinthedeveloper Oct 18 '20 at 20:02
  • @austinthedeveloper I am not sure you can have an array of references that can be populated automatically. But I don't know. – Yaron Oct 19 '20 at 09:24
2

None of above work for me, I had to use populate(). Reference from https://dev.to/mossnana/nestjs-with-mongoose-populate-4mo7?signin=true

An example of complete code and structure users.service.ts

import { User, UserDocument } from 'src/schemas/user.schema';
import { Role, RoleDocument } from 'src/schemas/role.schema';

...

constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(Role.name) private roleModel: Model<RoleDocument>,
    private roleService: RolesService
  ) {}


async findOne(id: string) {
    return await this.userModel.findOne({ _id: id }).populate('role', '', this.roleModel).exec();
}

user.schema.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Role } from './role.schema';

export type UserDocument = User & mongoose.Document;

@Schema()
export class User {
  @Prop({ required: true, type: String })
  email: string;

  @Prop({ type: String })
  name: string;

  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Role' })
  role: Role;
}

export const UserSchema = SchemaFactory.createForClass(User);

role.schema.ts

export type RoleDocument = Role & mongoose.Document;

@Schema()
export class Role {
  @Prop({ type: String, required: true, unique: true, index: true })
  name: string;

  @Prop({ type: [String], required: true })
  permissions: string[];
}

export const RoleSchema = SchemaFactory.createForClass(Role);
cjmling
  • 6,896
  • 10
  • 43
  • 79