如何使用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*****' } );
能帮我解决这个问题吗?
答案 0 :(得分: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的博客文章,但是要实现它,您可能需要重构一些代码。