Graphql returns null id for mongoose aggregation query, but works ok other mongoose queries.
Here is my mongoose schema:
const { Schema } = mongoose;
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
}