Search code examples
graphqlapolloreact-apolloapollo-clientapollo-server

How can I get user by userName in GraphQL?


I have this RootQuery:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        user: {
            type: UserType,
            args: { id: { type: GraphQLID } },
            resolve(parent, {id}) {
                return User.findById(id)
            }
        },

and then Ill use this query to get the user:

{
  user(id:"5bd78614e71a37341cd2b647"){
    id
    userName
    password
    isAdmin
  }
}

it works just fine' now i dont want to get the user by his ID, I want to get him by his userName insted so I used this

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        user: {
            type: UserType,
            args: { userName: { type: GraphQLString } },
            resolve(parent, {userName}) {
                console.log('userName',userName)
                return User.find({ userName })
            }
        },

this will bring back the user with all properties be null please help!!


Solution

  • First, you should use findOne to get only one user, find will bring you all users with that name. If you want that, maybe your return should be type: GraphQLList(UserType). If it's bringing all properties it is probably because you are asking for them on the query. Also, you might be missing an await User.find({ userName }), and an async on your function:

       const RootQuery = new GraphQLObjectType({
            name: 'RootQueryType',
            fields: {
                user: {
                    type: UserType,
                    args: { userName: { type: GraphQLString } },
                    resolve: async (parent, {userName}) => {
                        console.log('userName',userName)
                        const user = await User.findOne({ userName })
                        console.log('user',user);
                        return user;
                    }
                },
    

    Check if this helps you :)