Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb _id with graphql and document.toObject()

Let's use a basic mongodb query that returns one item:

const result = await db.myCollection.findById('xxxx')
return result;

This query result given to graphql works fine.

But now, if I return a result.toObject(), it's not working anymore.

I got this following error:

"message": "Cannot return null for non-nullable field MyCollection.id."

Why with toObject(), the mapping between _id and id can't be done?

like image 625
pellea Avatar asked Mar 07 '23 16:03

pellea


1 Answers

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.

like image 54
Daniel Rearden Avatar answered Mar 15 '23 22:03

Daniel Rearden