How can i post a DTO that contain an array of entities?

Viewed 2797

I have a couple of questions about NestJS and TypeOrm. First, how to pass an array of strings to DTO? I tried just to use :string[] type, but the compiler gives an error. This is my Post entity:

@Entity('posts')
export class Post {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => User, user => user.posts, { cascade: true })
    author: number;

    @Column({ type: 'timestamp' })
    date: Date;

    @Column()
    text: string;
    
    @Column({ default: 0 })
    likes: number;

    @OneToMany(() => Photo, photo => photo.post, { cascade: true })
    photos: Photo[];
}

And CreatePostDto:

export class CreatePostDto {
    authorId: number;
    date: Date;
    text?: string;
    // photos?: string[];
}

And the second question: How can i save to the repository every photo (keeping the connection with post), posts to the posts repo and update user by adding new post binded to him. I tried something like this, but it won't work obviously.

    async create(createPostDto: CreatePostDto) {
      const post = this.postsRepository.create(createPostDto);
      const user = await this.usersRepository.findOne(createPostDto.authorId);
      
      return this.postsRepository.save({author: user, date: createPostDto.date, text: createPostDto.text});
  }
1 Answers

What you missed here is saving photos before bind them with the post, here's an example:

async create(createPostDto: CreatePostDto) {
 let photos:Array<Photo> = [] ; array of type photo entity
   for(let urlPhoto of createPostDto.photos)
   {
    let  photo =  await this.imageRepository.save({url : urlPhoto }); you must save the photos first
    photos.push(photo); 
   }
  const user = await this.usersRepository.findOne(createPostDto.authorId);
  
  return this.postsRepository.save({author: user, date: createPostDto.date, text: 
   createPostDto.text,photos:photos});
  }
Related