mongodb _id 与 graphql 和 document.toObject()

mongodb _id with graphql and document.toObject()

让我们使用一个基本的 mongodb 查询 return 一项:

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

给 graphql 的这个查询结果工作正常。

但是现在,如果我 return 一个 result.toObject(),它就不再工作了。

我收到以下错误:

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

为什么toObject()无法实现_idid之间的映射?

MongoDB 生成的 id 将是一个 _id 字段——猫鼬就是 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.

这里的关键是 id 字段是一个 虚拟 getter。为了将它们包含在生成的对象中,您必须将适当的选项传递给 toObject:

result.toObject({ virtuals: true })

有关详细信息,请参阅 docs or this answer