Reputation: 526
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) ?
Upvotes: 4
Views: 10870
Reputation: 1
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);
}
},
},
Upvotes: 0
Reputation: 84747
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()
}
Upvotes: 4
Reputation: 994
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"
}
}),
},
Upvotes: 1