mongodb _id with graphql and document.toObject() mongodb _id with graphql and document.toObject() mongoose mongoose

mongodb _id with graphql and document.toObject()


The id generated by MongoDB will be a _id field -- it's mongoose that's actually mapping it for you.

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. If you don't want an id getter added to your schema, you may disable it passing this option at schema construction time.

They key here is that the id field is a virtual getter. In order to include those in the generated object, you have to pass the appropriate option to toObject:

result.toObject({ virtuals: true })

See the docs or this answer for more details.