Graphql 为猫鼬聚合查询返回空 ID [英] Graphql returns null id for mongoose aggregation query

查看:29
本文介绍了Graphql 为猫鼬聚合查询返回空 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Graphql 为 mongoose 聚合查询返回 null id,但在其他 mongoose 查询中工作正常.

Graphql returns null id for mongoose aggregation query, but works ok other mongoose queries.

这是我的猫鼬模式:

const { Schema } = mongoose;
const ObjectId = Schema.Types.ObjectId;

const productSchema = new Schema({
  _id: ObjectId,
  price: Number
})

const Product = mongoose.model('Product', productSchema, 'Product')

这是我的 Graphql 架构:

Here is my Graphql schema:

type Product {
    id: ID
    price: String
}

Graphql 普通查询:

Graphql normal query:

   context.Product.findOne()

console.log 的结果:

Result with console.log:

[ {
    price: 10,    
    _id: 5d7f8efebff791dcd3bb1b69
}]

graphql 的结果:

Result with graphql:

 "getSearch": [
      {
        "id": "5d7f8efebff791dcd3bb1b69",
        "price": 10,
  }]

这里一切正常.现在的问题是聚合查询:

GraphQL 查询:

GraphQL query:

context.Product.aggregate(
          [
            { $sample: { size: 1 } }
          ]
    )

console.log 的结果:

Result with console.log:

[ { _id: 5d7f8f23bff791dcd3bb1da3,
    price: 5
}]

GraphQL 结果:

Result with GraphQL:

 "test": [
          {
            "id": null",
            "price": 7,
      }]

这里的问题是:

  • id 为空
  • 来自 console.log 和 graphql 的响应是不同的对象

推荐答案

MongoDB 中的文档通常没有 id 属性,只有 _id 属性.这显示在您看到的控制台输出中.然而,猫鼬模型实例确实有一个用于 id 的 getter,它返回 id 的值.来自文档:

Documents in MongoDB normally don't have an id property, just an _id property. This is shown in the console output you're seeing. However, mongoose model instances do have a getter for id that returns the value of id. From the docs:

默认情况下,Mongoose 为您的每个模式分配一个 id 虚拟 getter,它将文档 _id 字段转换为字符串,或者在 ObjectIds 的情况下,返回其 hexString.

Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

findfindOne 等方法返回的是 模型 具有此吸气剂.但是,使用 aggregate 会导致返回纯 JavaScript 对象(没有 getter).

What's returned by methods like find and findOne are instances of the Model that have this getter. However, using aggregate results in plain JavaScript objects being returned instead (with no getter).

您可以为 id 字段编写解析器以从 id_id 中提取值:

You can write a resolver for the id field to pull the value from either id or _id:

function resolve (parent, args, context, info) {
  return parent.id || parent._id
}

这篇关于Graphql 为猫鼬聚合查询返回空 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆