Mongoose with NestJS - One to Many Mongoose with NestJS - One to Many mongoose mongoose

Mongoose with NestJS - One to Many


I have solved my issue with ONE-TO-MANY relationship in this way:

package.json:

"@nestjs/mongoose": "7.0.2""mongoose": "^5.10.14"

For doing an example, I'll use the schemas from this issue(User and Token):

  1. Creating Token Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';import { Document, Types } from 'mongoose';@Schema({_id: false})export class Token {  @Prop({type: Types.ObjectId})  _id: Types.ObjectId;  @Prop()  token: string;  @Prop()  refreshToken: string;  @Prop()  createdAt: Date; // You can use Date here.  @Prop()  expiresAt: Date;  @Prop()  isValid: boolean;}export const TokenSchema = SchemaFactory.createForClass(Token);
  1. Adding Token Schema into TokenModule
import { MongooseModule } from '@nestjs/mongoose';@Module({  imports: [    MongooseModule.forFeature([      { name: Token.name, schema: TokenSchema },    ]),  ],  // ...})export class TokenModule {}
  1. Creating User Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';import { Document, Types } from 'mongoose';export type UserDocument = User & Document;@Schema({_id: false})export class User {  @Prop({type: Types.ObjectId})  _id: Types.ObjectId;  @Prop()  name: string;  @Prop()  email: string;  @Prop()  role: number;  @Prop(type: [Types.ObjectId], ref: Token.name)  tokens: Token[];}export const UserSchema = SchemaFactory.createForClass(User);
  1. Adding User Schema into UserModule
import { MongooseModule } from '@nestjs/mongoose';@Module({  imports: [    MongooseModule.forFeature([      { name: User.name, schema: UserSchema },    ]),  ],  // ...})export class UserModule {}
  1. Using the populate function in the UserService
@Injectable()export class UserService {  constructor(    @InjectModel(User.name) private userModel: Model<UserDocument>,  ) {}  async getUserWithPopulate(id: string) {    // Here is the ace in the hole, you need to specify the path (tokens) and the model (Token.name).    await this.userModel      .find()      .populate('tokens', null, Token.name)      .exec()  }}