Node.js 通过GraphQL检索单个和多个对象

Node.js 通过GraphQL检索单个和多个对象,node.js,graphql,Node.js,Graphql,我使用Apollo和GraphQL还不到几个星期,我想通过GraphQL检索多个对象,但它不允许我这样做 将查询设置为: const GET_ALL_PURCHASES_QUERY = (statusOfPurchase) => { return gql` query { getAllPurchases(statusOfPurchase: "${statusOfPurchase}") { id customerInformatio

我使用Apollo和GraphQL还不到几个星期,我想通过GraphQL检索多个对象,但它不允许我这样做

将查询设置为:

const GET_ALL_PURCHASES_QUERY = (statusOfPurchase) => {
  return gql`
  query {
    getAllPurchases(statusOfPurchase: "${statusOfPurchase}") {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}
const GET_ALL_PURCHASES_QUERY = () => {
  return gql`
  query {
    getAllPurchases {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}
。。。在模式中:

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    getAllPurchases: {
      type: PurchaseType,
      args: {
        statusOfPurchase: {
          type: new GraphQLNonNull(GraphQLString)
        }
      },
      resolve(parent, args) {
        return PurchasesModel.schemaForPurchases.find({
          statusOfPurchase: args.statusOfPurchase
        }).limit(10)
          .then(purchases => {
            console.log('Schema:getAllPurchases()', purchases)
            return purchases
          })
      }
    }
  }
})
通过终端进入节点的结果为:

Schema:getAllPurchases() [
  {
    _id: 60351a691d3e5a70d63eb13e,
    customerInformation: [ [Object] ],
    statusOfPurchase: 'new',
    createdAt: 2021-02-23T15:08:25.230Z,
    updatedAt: 2021-02-23T15:08:25.230Z,
    __v: 0
  },
  {
    _id: 60351b966de111716f2d8a6d,
    customerInformation: [ [Object] ],
    statusOfPurchase: 'new',
    createdAt: 2021-02-23T15:13:26.552Z,
    updatedAt: 2021-02-23T15:13:26.552Z,
    __v: 0
  }
]

但在Chrome的应用程序中,它是一个单独的对象,每个字段的值都是null

将查询设置为:

const GET_ALL_PURCHASES_QUERY = (statusOfPurchase) => {
  return gql`
  query {
    getAllPurchases(statusOfPurchase: "${statusOfPurchase}") {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}
const GET_ALL_PURCHASES_QUERY = () => {
  return gql`
  query {
    getAllPurchases {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}
。。。通过对模式进行适当的更改,结果与之前相同,在Node中我看到两个对象,但在Chrome中看到一个失败的对象

如果我将:
return purchases
更改为:
return purchases[0]
我会在Chrome中看到第一个具有正确值的对象


如何返回多个对象?

在架构中,您的
getAllPurchases
字段的类型设置为
PurchaseType
。您希望使用
new-graphqlist(PurchaseType)
使退货类型成为采购列表。这就是为什么当您尝试使用模式时,如果类型不好,它将返回null;如果您返回单个元素,它将正确地返回purchase


请参见此示例。

Alex,非常感谢。