简体   繁体   English

mongodb _id与graphql和document.toObject()

[英]mongodb _id with graphql and document.toObject()

Let's use a basic mongodb query that returns one item: 让我们使用一个基本的mongodb查询,该查询返回一项:

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

This query result given to graphql works fine. 将此查询结果提供给graphql可以正常工作。

But now, if I return a result.toObject() , it's not working anymore. 但是现在,如果我返回result.toObject() ,它将不再起作用。

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? 为什么使用toObject()不能完成_idid之间的映射?

The id generated by MongoDB will be a _id field -- it's mongoose that's actually mapping it for you . MongoDB生成的id将是一个_id字段-它是猫鼬实际上正在为您映射它

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. Mongoose默认情况下为您的每个模式分配一个id虚拟getter,该属性将文档_id字段强制转换为字符串,对于ObjectIds,则返回其hexString。 If you don't want an id getter added to your schema, you may disable it passing this option at schema construction time. 如果您不希望在架构中添加id getter,则可以在架构构建时通过此选项将其禁用。

They key here is that the id field is a virtual getter . 他们的关键是id字段是一个虚拟的getter In order to include those in the generated object, you have to pass the appropriate option to toObject : 为了将那些包含在生成的对象中,您必须将适当的选项传递给toObject

result.toObject({ virtuals: true })

See the docs or this answer for more details. 请参阅文档此答案以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM