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
):
- 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);
- Adding
Token
Schema intoTokenModule
import { MongooseModule } from '@nestjs/mongoose';@Module({ imports: [ MongooseModule.forFeature([ { name: Token.name, schema: TokenSchema }, ]), ], // ...})export class TokenModule {}
- 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);
- Adding
User
Schema intoUserModule
import { MongooseModule } from '@nestjs/mongoose';@Module({ imports: [ MongooseModule.forFeature([ { name: User.name, schema: UserSchema }, ]), ], // ...})export class UserModule {}
- Using the
populate
function in theUserService
@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() }}