如何在graphql中从mongo填充相关集合?

时间:2019-03-24 07:42:58

标签: node.js mongodb mongoose graphql

如何使用带有猫鼬的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查询那些字段nameUser。这段代码可以很好地工作:

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')

0 个答案:

没有答案