首页 > 解决方案 > 使用 id vs _id 实现用户记录的正确方法

问题描述

我无法理解实现 MongoDB 用户记录类型以与 GraphQL 一起使用的正确方法。具体来说,它与用户标识有关。

我希望能够查询用户记录并获取用户 ID 作为“ID”。MongoDB 记录默认有一个 _id。

我该如何做到这一点?

我是否必须将用户记录定义为:

type User {
  id: ID!
  name: String!
  email: String!
}

然后我应该在创建记录时自己填充“id”字段吗?

或者我应该只使用 _id 作为用户 ID?如果是这样,我该如何查询?我收到问题说我无法查询它。我认为是因为它不在 typedef 中。

标签: mongodbexpressgraphqlschemaapollo-server

解决方案


I'm using TypeGraphQL along with TypeORM, and there you can create mapping by using decorators:

  @Field(type => ID!, { name: 'id' })
  @Column({ type: '_id', nullable: false, unique: true })
  public _id: string;

推荐阅读