How to query User
object with UserType
using graphql with mongoose?
I have looked in Ahmad Ferdous answer but I could not figure out how to do with different collection..
export const UserType = mongoose.model('User-Type', new mongoose.Schema({
typeName: { type: String }
}));
export const User = mongoose.model('User', new mongoose.Schema({
name: { type: String },
type: { type: mongoose.Schema.Types.ObjectId, ref: 'User-Type' },
})
);
const Users = new GraphQLObjectType({
name: 'Users',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
type: { type: /* HOW TO CONNECT TO USER TYPE? */ },
}),
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
users: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({});
},
},
});
export const Schema = new GraphQLSchema({
query: RootQuery,
});
In mongoose to resolve User
with UserType
I does:
const users = await User.find({})
.populate({ path: 'type', model: 'User-Type' })
UPDATE
This question is not duplicate. Why? I want to query those fields id
, name
from User
. this is working well by this code:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
users: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({});
},
},
});
But when query with type
field then I should do:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
users: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({}).populate({ path: 'type', model: 'User-Type' });
},
},
});
This is seem so much wrong with graphql because if I just want id, name the mongoose also ask for type ( return await User.find({}).**populate**({ path: 'type', model: 'User-Type' });
) that I did not ask!
So I think I should do:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
onlyUsers: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({});
},
},
UsersWithType: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({}).populate({ path: 'type', model: 'User-Type' });
},
},
});
This is how do things in graphql
??
I want to query User and get from the db only the fields I ask for.
If graphql doesn't do that that is power of using it? I can also use lodash for get the fields I want from the object.. _.get(obj, 'somefield.anothersomefield')