【问题标题】:Mongoose Document.toObject produces GraphQL errorMongoose Document.toObject 产生 GraphQL 错误
【发布时间】:2019-05-11 21:27:31
【问题描述】:

我在一个项目中同时使用mongooseexpress-graphql。我想使用 here 描述的 .toObject() 方法将文档转换为对象,然后将值返回给 GraphQL。

GraphQL 架构:

type User {
    _id: ID,
    // ...
}

代码:

const Me = function (params, req) {
    if (!req.user) throw Error('Not logged in');
    return req.user.toObject();
};

module.exports = Me;

但是,我收到以下错误:

ID 不能代表值:{ _bsontype: "ObjectID", id: }

我尝试使用console.log(req.user.toObject()._id)_id 打印到屏幕上,但它只是显示了id 字符串。出于某种原因,以下代码有效:

const Me = function (params, req) {
    if (!req.user) throw Error('Not logged in');
    return JSON.parse(JSON.stringify(req.user.toObject()));
};

module.exports = Me;

我不确定是什么导致 GraphQL 直接从 .toObject() 方法将 _id 字段作为非字符串值读取。谢谢您的帮助!

【问题讨论】:

  • graphql 版本是什么?
  • @ShivamPandey GraphQL 14.0.2

标签: mongoose graphql


【解决方案1】:

当您使用14.0.2 时,a change 对最新版本中引入的 graphql 包存在问题,而 already a PR 可以解决此问题。如果你切换到 0.13.2 效果会更好。

【讨论】:

  • 谢谢。在调用.toObject() 后,我可以通过设置user._id = String(user._id) 来临时修复问题。
猜你喜欢
  • 2018-08-25
  • 2018-11-09
  • 2020-04-15
  • 2021-07-28
  • 2017-06-10
  • 2020-10-05
  • 2020-08-05
  • 2016-07-03
  • 2020-06-28
相关资源
最近更新 更多