Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

380
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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:

await 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,
    });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda