Graphql returns null id for mongoose aggregation query

前端 未结 2 373
深忆病人
深忆病人 2021-01-19 17:21

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

Here is my mongoose schema:

const { Schema } = mongoose;         


        
相关标签:
2条回答
  • 2021-01-19 18:06

    Just add both IDs if you don't want to change every single instance of it.

    type Product {
      id: ID
      _id: ID
      price: String
    }
    
    0 讨论(0)
  • 2021-01-19 18:21

    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 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.

    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).

    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
    }
    
    0 讨论(0)
提交回复
热议问题