DEV Community

Luiz Pires
Luiz Pires

Posted on

1

relacionamento 1:n mongose

Para criar um relacionamento 1:n (um para muitos) utilizando o Mongoose e o NestJS, você pode seguir os seguintes passos:

  1. Defina os Modelos: Comece definindo os modelos para as entidades envolvidas no relacionamento.
// post.model.ts
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Post extends Document {
  @Prop()
  title: string;

  @Prop()
  content: string;
}

export const PostSchema = SchemaFactory.createForClass(Post);
Enter fullscreen mode Exit fullscreen mode
// comment.model.ts
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Comment extends Document {
  @Prop()
  text: string;
}

export const CommentSchema = SchemaFactory.createForClass(Comment);
Enter fullscreen mode Exit fullscreen mode
  1. Defina as Relações: No modelo Post, você pode criar um campo que armazene um array de IDs de comentários para representar a relação 1:n.
// post.model.ts
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Comment } from './comment.model';

@Schema()
export class Post extends Document {
  @Prop()
  title: string;

  @Prop()
  content: string;

  @Prop({ type: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] })
  comments: Comment[];
}

export const PostSchema = SchemaFactory.createForClass(Post);
Enter fullscreen mode Exit fullscreen mode
  1. Crie os Serviços: Agora, você precisa criar os serviços para interagir com os modelos.
// post.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Post } from './post.model';

@Injectable()
export class PostService {
  constructor(@InjectModel(Post.name) private postModel: Model<Post>) {}

  async findAll(): Promise<Post[]> {
    return this.postModel.find().populate('comments').exec();
  }

  // ... outros métodos
}
Enter fullscreen mode Exit fullscreen mode
// comment.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Comment } from './comment.model';

@Injectable()
export class CommentService {
  constructor(@InjectModel(Comment.name) private commentModel: Model<Comment>) {}

  // ... métodos para criar comentários, etc.
}
Enter fullscreen mode Exit fullscreen mode
  1. Configure os Módulos: Configure os módulos no NestJS para que eles possam ser injetados onde necessário.
// post.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { PostService } from './post.service';
import { Post, PostSchema } from './post.model';

@Module({
  imports: [MongooseModule.forFeature([{ name: Post.name, schema: PostSchema }])],
  providers: [PostService],
  exports: [PostService],
})
export class PostModule {}
Enter fullscreen mode Exit fullscreen mode
// comment.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CommentService } from './comment.service';
import { Comment, CommentSchema } from './comment.model';

@Module({
  imports: [MongooseModule.forFeature([{ name: Comment.name, schema: CommentSchema }])],
  providers: [CommentService],
  exports: [CommentService],
})
export class CommentModule {}
Enter fullscreen mode Exit fullscreen mode
  1. Utilize os Serviços: Agora você pode utilizar os serviços para criar, listar e manipular posts e comentários.

Lembrando que este é um exemplo básico de como criar um relacionamento 1:n entre posts e comentários usando Mongoose e NestJS. Dependendo das suas necessidades, você pode precisar adicionar mais funcionalidades e validações aos seus serviços e controladores.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay