mongodb - 带有空id的graphql查询返回对象

标签 mongodb graphql aggregate

Graphql 返回带有空 ID 的对象。 与 mongodb。

我觉得很奇怪。

如果我删除 MailType id 上的 new GraphQLNonNull(), 它适用于 id: null,其他字段工作正常。

const MailType = new GraphQLObjectType({
    name: 'Mail',
    fields: () => ({
        id: { type: new GraphQLNonNull(GraphQLID), },
...
})

const Query = {
    mails: {
        type: new GraphQLList(MailType),
        args: {
            senderId: { type: GraphQLID },
            isOffline: { type: GraphQLBoolean },
        },
        async resolve(root, args, req, ctx) {
            if (args.isOffline === false) {
                let a = await model.aggregate([
                  { $match: { isOffline: false } },
                ]);
                let b = await model.find({ isOffline: false });

                console.log(JSON.stringify(a) == JSON.Stringify(b)) /// return true
                return a // error
                return b // working
            }
            return model.find({senderId: args.senderId});
        }
    }
}
// with a
    "errors": [
        {
            "message": "Cannot return null for non-nullable field Mail.id."
        }]

我遇到了 2 个小时的麻烦,但我没有得到答案。 谁能帮帮我?

最佳答案

您可能在 mongodb 模式中有错误,而不是在 graphQl 中。 确保您没有通过 id 键定义您的 id,它应该是 _id

例如,如果您使用 Mongoose ,它可以是这样的:

const MailSchema = new Schema({
  _id: {
    type: String,
    unique: true,
  },
  ....
  ....
});

关于mongodb - 带有空id的graphql查询返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265325/

相关文章:

javascript - MongoDB引用错误: Schema is not defined

node.js - 不确定如何解释 Collection.insert 的 MongoDB Node.js 驱动程序回调参数

node.js - 转换发布带有显示次数的 MeteorJS

python - 使用最新的 Graphite 烯和 Graphite 烯-django版本时导入(无法从 'ResolveInfo' 导入名称 'graphql' )错误

reactjs - 如何使用 Gatsby 显示 Contentul 图像

r - 将多个 csv 文件平均为 r 中的 1 个平均文件

sql - 如何制定聚合不同值的 SQL Server 索引 View ?

python - MongoEngine:限制来自 DBRef 的响应数量

graphql 只解析 _id 字段,其他字段为空

c# - 如何使用 Linq 的聚合函数 C# 添加到列表