从@ManyToOne() 关系中获取数据 mikro orm mongodb

问题描述

我有一个 Post 实体:

export class Post {
  @PrimaryKey()
  _id!: ObjectId;

  @Field(() => ID)
  @SerializedPrimaryKey()
  id!: string;

  @Field(() => String)
  @property()
  createdAt: Date = new Date();

  @Field(() => String)
  @Property({ onUpdate: () => new Date() })
  updatedAt: Date = new Date();

  @Field(() => String)
  @property()
  title!: string;

  @Field(() => String)
  @property()
  excerpt!: string;

  @Field(() => String)
  @property()
  content!: string;

  @Field(() => User)
  @ManyToOne()
  author!: User;
}

用户实体:

@ObjectType()
@Entity()
export class User {
  @PrimaryKey()
  _id!: ObjectId;

  @Field(() => ID)
  @SerializedPrimaryKey()
  id!: string;

  @Field(() => String)
  @property()
  createdAt = new Date();

  @Field(() => String)
  @Property({ onUpdate: () => new Date() })
  updatedAt = new Date();

  @Field(() => String)
  @property()
  name!: string;

  @Field(() => String)
  @Property({ unique: true })
  email!: string;

  @property()
  password!: string;

  @Field(() => [Post],{ nullable: true })
  @OnetoMany(() => Post,(post) => post.author)
  posts = new Collection<Post>(this);
}

创建帖子功能

 @Mutation(() => Post)
  async createPost(
    @Arg("post") post: PostInput,@Ctx() { em,req }: appContext
  ) {
    const newPost = em.create(Post,{
      ...post,author: new ObjectId(req.session.sid),});
    await em.persistAndFlush(newPost);
    return newPost;
  }

如您所见,User 和 Post 分别是一对多的关系。 user.posts 工作正常,因为我们需要添加 init()。但是当我尝试记录 post.author 时,它给了我以下信息:

Ref<User> { _id: ObjectId('600663ef9ee88b1b9c63b275') }

搜索了文档,但找不到如何填充作者字段。

解决方法

要填充关系,您可以使用 wrap 助手:

await wrap(newPost.author).init();

如果实体已经加载,将其标记为已填充就足够了:

await wrap(newPost.author).populated();

(但这里没有加载,你可以在登录时通过 Ref<> 判断,它只针对未加载的实体)

https://mikro-orm.io/docs/entity-helper/#wrappedentity-and-wrap-helper

如果您希望加载的实体和新持久化的实体具有相同的结果,您可以在 ORM 配置中使用 populateAfterFlush: true。这样,所有关系都将在调用 em.flush() 后填充。但这在这里也无济于事,因为您正在处理未加载的现有实体的 PK(例如,在使用 newPost.author = new Author() 时会有所帮助)。

顺便说一句,这里不需要使用对象ID,这也应该没问题:

    const newPost = em.create(Post,{
      ...post,author: req.session.sid,});