如何使用带有猫鼬的graphql用User
查询UserType
对象?
我看过Ahmad Ferdous answer,但我不知道如何处理其他集合。
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,
});
用猫鼬用User
来解决UserType
的问题:
const users = await User.find({})
.populate({ path: 'type', model: 'User-Type' })
更新
此问题不是重复的。为什么?我想从id
查询那些字段name
,User
。这段代码可以很好地工作:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
users: {
type: new GraphQLList(Users),
async resolve(parent, args) {
return await User.find({});
},
},
});
但是当用 {strong> type
”字段查询时,我应该这样做:
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' });
},
},
});
graphql似乎有很多错误,因为如果我只想要id,命名猫鼬还会要求输入我没有问过的类型(return await User.find({}).**populate**({ path: 'type', model: 'User-Type' });
)!
所以我认为我应该这样做:
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' });
},
},
});
这是graphql
中的事情?
我想查询User并仅从数据库中获取我要求的字段。
如果graphql不这样做,那就是使用它的力量?我也可以使用lodash从对象中获取所需的字段。_.get(obj, 'somefield.anothersomefield')