4
votes

So I have this simple schema:

type User {
        _id: String,
        username: String,
        age: Int,
        email: String,
        password: String,
    }
    type Query {
        user(_id: String!): User,
    }

Resolver:

import User from './User';

export default {
    Query: {
        user: (_, { _id }) => User.findById(_id),
    },
}

how can I get a user by some specified fields like username, email without creating a query function for each one (if the user would have 1000 unique fields it would be pretty painful to create 1000 queries for each type) ?

3
It would be helpful to update this question to include more details. What are you using for a storage layer? If you're using a DB, what ORM or query builder are you using to interface with it? What have you tried already? It might also be helpful to see the resolver for the user query. - Daniel Rearden
I'm using apollo-server and Mongodb for storage, I updated the question with the resolver function. - Alex C

3 Answers

4
votes

If the names of your arguments match the names of your fields, it's easy enough to pass the entire args object as a parameter to find() or findOne():

Query: {
  user: (_, args) => User.findOne(args),
},

In this case, you'll get the first user matching the arguments passed in and return it. In the event you want to return all possible matches, you can have two separate queries, one returning a single User, and another returning a List of Users:

Query: {
  user: (_, args) => User.findOne(args),
  users: (_, args) => User.find(args),
},

If there are any arguments that need to be treated differently (for example, if you wanted to pass in a limit or add some kind of pagination), you can always use a helper library like lodash or ramda to pull out just those arguments. For example:

users: (_, args) => {
  const where = omit(args, ['limit'])
  const limit = args.limit || 10
  return User.find(where).sort({'someField': -1}).limit(limit).exec()
}
1
votes

You can resolve your query like this

Query: {
    user: (_, args) => User.findOne({
      where: {
        email: "Your search value"
      }
    }),
  },

  Query: {
    user: (_, args) => User.findOne({
      where: {
        username: "Your search value"
      }
    }),
  },
0
votes

You can resolve it like this :


  Query: {
    async getPosts(_, { username }) {
      try {
        const posts = await Post.find({ username: username });
        return posts;
      } catch (err) {
        throw new Error(err);
      }
    },
  },