我有一个 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') }
我搜索了文档,但找不到如何填充作者字段。