如何解决从@ManyToOne() 关系中获取数据 mikro orm mongodb
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,});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。