nestjs - 如何发布包含实体数组的 DTO?

标签 nestjs typeorm

我有几个关于 NestJS 和 TypeOrm 的问题。 首先,如何将字符串数组传递给DTO?我尝试只使用 :string[] 类型,但编译器给出错误。 这是我的帖子实体:

@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[];
}

和CreatePostDto:

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

第二个问题:我如何将每张照片保存到存储库(保持与帖子的连接),将帖子发布到帖子存储库并通过添加绑定(bind)到他的新帖子来更新用户。 我尝试过类似的方法,但显然行不通。

    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});
  }

最佳答案

您在这里错过的是在将照片与帖子绑定(bind)之前保存照片,这是一个示例:

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});
  }

关于nestjs - 如何发布包含实体数组的 DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604757/

相关文章:

typescript - Nestjs:类型不满足约束 'Document'

json - NestJS Swagger : Describe Map inside ApiProperty Decorator

mysql - 具有别名的计算列未映射到 TypeORM 实体

nestjs - 如何删除 TypeORM 和 Nest.js 中的嵌套实体

node.js - 在我的模块中的 Nestjs 中导入另一个模块的存储库

typescript - TypeORM, ManyToMany 按类别 id (TreeEntity 物化路径) 获取帖子

javascript - WebSocketGateway 中的 WsException 不起作用

jestjs - 无法模拟 createQueryBuilder 函数 typeorm Nestjs Jest

MongoDB : aggregate query matching a specific date from array of start and end dates

javascript - TypeORM 自定义存储库不覆盖 createQueryBuilder