Graphql returns null id for mongoose aggregation query Graphql returns null id for mongoose aggregation query mongoose mongoose

Graphql returns null id for mongoose aggregation query


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}


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

type Product {  id: ID  _id: ID  price: String}


If you are using mongoose with nest js and GraphQL, I have fixed it by changing the id to _id and removing the @prop above it Example on github

  @Prop()//remove this  @Field(() => ID,{ nullable: true })  _id: string;