【问题标题】:GraphQL query on Embedded/Nested Field in MongoDBMongoDB 中嵌入式/嵌套字段的 GraphQL 查询
【发布时间】:2019-08-12 15:49:57
【问题描述】:

如何使用 GraphQL 对 MongoDB 中嵌入/嵌套文档中的字段指定查询条件?

在 mongo shell 中,我可以通过

轻松获取文档
db.users.find({ 'contacts.phone': '8148*****' } ).pretty();

这会给我带来记录

{
        "_id" : ObjectId("5c93c0601a29f5183929c02c"),
        "name" : "Athul",
        "contacts" : {
                "address" : "Some address",
                "phone" : "8148*****",
                "email" : "***@live.com"
        },
        "__v" : 0
}

在我的 GraphQL Schema上,我已经定义了如下所述的查询

...
input ContactsInput {
    address: String
    phone: String
    email: String
}

input userInput {
  name: String
  contacts: ContactsInput
}

type RootQuery {
  users(user: userInput): [User!]!
}
....

用户的解析器是

...
const User = require('../../models/user');
...
    users: async args => {
        try{
            const query = JSON.parse(JSON.stringify(args.user));
            const userList = await User.find(query);

            if(!userList) {
                throw new Error("No user found");
            }

            return userList;
        } catch(err){
            throw err;
        }
    }
...

(如果我用名字搜索就可以了)

在 GraphiQL 中,我试图通过以下查询获取相同的记录

query{
  users(user: {contacts: {
    phone: "8148*****" 
  }}){
    name
    contacts{
      email
      phone
    }
  }
}

我无法获得相同的记录。

因为它在后端执行

db.users.find({ contacts: { phone: '8148405590' } });

不等价于

db.users.find({ 'contacts.phone': '8148*****' } );

你能帮我解决这个问题吗?

【问题讨论】:

  • 您可以编辑您的问题并为users 提供您的解析器吗?
  • @MarcoDaniels 我已经用用户解析器更新了这个问题。

标签: mongodb express graphql schema


【解决方案1】:

看起来您必须先构建查询对象,然后再将其发送到mongodb。

你可以试试这样的:

const tempQuery = {'contacts.phone': args.user.contacts.phone}

const query = JSON.parse(JSON.stringify(tempQuery));

您只需要确保输入中存在所有值(user.contacts.phone),如果您想要其他查询,您必须编写所有不同的组合(例如:contacts.email)。

否则,您可以查看有关 GraphQL to MongoDB 和库 graphql-to-mongodb 的博客文章,但要实现它,您可能需要重构一些代码。

【讨论】:

  • 有什么替代品吗?否则我必须以同样的方式处理对contacts.email 和contacts.address 的查询。
  • @AthulMR 我用可能解决您问题的外部工具更新了我的答案。
猜你喜欢
  • 2019-07-08
  • 2021-01-29
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2019-07-18
  • 2020-01-29
  • 2017-01-27
相关资源
最近更新 更多