Search code examples
node.jsmongodbmikro-orm

Get data from @ManyToOne() relation mikro orm mongodb


I have a Post entity:

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

User Entity:

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

Create Post function:

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

As you can see, User and Post are related with one to many relations respectively. user.posts is working correctly, as we need to add init(). But when I tried to log post.author it is giving me the following:

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

I have searched the docs but couldn't find how to populate the author field.


Solution

  • To populate a relation, you can use the wrap helper:

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

    If the entity would be already loaded, it would be enough to mark it as populated:

    wrap(newPost.author).populated();
    

    (but here it is not loaded, you can tell by the Ref<> when you log it, it is there only for not loaded entities)

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

    If you want to have same result for loaded entities and newly persisted entities, you can use populateAfterFlush: true in the ORM config. That way, all relations will be populated after calling em.flush(). But that would also not help here, as you are working with a PK of existing entity that is not loaded (e.g. it would help when using newPost.author = new Author()).

    Btw it should not be needed to use object id here, this should be fine too:

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