【发布时间】: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