最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mongodb _id with graphql and document.toObject() - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Mar 16, 2018 at 13:27 Daniel Rearden 85k14 gold badges203 silver badges192 bronze badges asked Mar 16, 2018 at 12:31 pelleapellea 4765 silver badges24 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论