首页 > 解决方案 > GraphQL 和 MongoDB - 从 mongodb 自动插入的数据中获取“createdAt”字段

问题描述

假设我有模型:

const SomeSchema = new Schema(
  {
    name: String,
  },
  {timestamps: true},
);

这有时间戳,当我执行突变时,它会自动插入到 mongoDB 中createdAtupdatedAt

在我的 GraphQL 类型中:

const SomeType = new GraphQLObjectType({
  name: "SomeType",
  fields: () => ({
    _id: { type: GraphQLID },
    name: { type: GraphQLString },
  })
});

我没有 createdAt 或 updatedAt 字段,因为 mongoDB 为我处理了它。

createdAt如果我正在使用,我将如何获得价值useQuery

const GET_SOME = gql`
  query($name: String) {
    some(name: $name) {
      _id
      createdAt // how would I need to call this?
    }
  }
`;

我需要插入createdAt字段SomeType吗?

标签: mongodbgraphqlreact-apolloapollo-client

解决方案


您可以CreatedAt用作GraphQLString类型,并插入到SomeType字段中。

尝试这个:

const SomeType = new GraphQLObjectType({
  name: "SomeType",
  fields: () => ({
    _id: { type: GraphQLID },
    name: { type: GraphQLString },
    createdAt : { type : GraphQLString }
  })
});

推荐阅读