通过带参数的石墨烯查询 mongoDB

Querying mongoDB via graphene with arguments

早上好,

我希望能够提出一个 GraphQL 请求 "ask" MongoDB 以下问题:

query 
{ user(firstname:"Pierre}
    { lastname}
}
from mongoengine import Document
from mongoengine.fields import StringField
class User(Document):
    meta = {'collection': 'user'}
    firstname = StringField(required=True)
    lastname = StringField(required=True)
from graphene_mongo import MongoengineObjectType
from graphene import connect
from models import User as UserModel

connect(db="graphene-mongo-example",host="127.0.0.1:27017",alias="default")

class User(MongoengineObjectType):
    class Meta:
        model = UserModel

class Query(graphene.ObjectType):

    users = graphene.List(User)

    def resolve_users(self, info,firstname):
        return list(UserModel.objects.all(firstname))

schema = graphene.Schema(query=Query)

我没有成功只有具有给定名字的用户.. 你能帮帮我吗?

非常感谢

B.

查询 { 用户(名字:“皮埃尔} {姓氏}}

如果上面是你的 graphql 查询,那么它应该是

查询

{ 用户(名字:"Pierre"){ 姓} }

接下来在您的代码中读取这个参数 firstname 并相应地获取文档

models.py没有变化。 这是我为回答我遇到的问题而编写的代码:

import graphene
from graphene.relay import Node
from flask import Flask
from flask_graphql import GraphQLView
from graphene_mongo import MongoengineObjectType
from models import User as UserModel
from mongoengine import connect


connect(db="graphene-mongo-example",host="127.0.0.1:27017",alias="default")


class User(MongoengineObjectType):
    class Meta:
        model = UserModel
        filter_fields = ['fisrt_name']
        interfaces = (Node,)

class Query(graphene.ObjectType):
    user_by_name = graphene.Field(User,gName=graphene.String())

    def resolve_user_by_name(parent,info,gName):
       return UserModel.objects.get(first_name=gName)

schema = graphene.Schema(query=Query)

#==================================================================

app = Flask(__name__)
app.debug = True
app.add_url_rule(
    "/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True)
  )

if __name__ == "__main__":
    app.run()

然后我可以使用 GraphQL 查询这种请求:

query { 
userByName(gName:"Pierre")
  {lastName 
   firstName
  }
}