GraphQL和猫鼬多对多查询

时间:2020-10-12 21:57:44

标签: node.js express mongoose graphql many-to-many

我一直在使用express,mongodb和GraphQL构建应用程序。

现在,我能够建立用户与组的多对多关系。 我可以添加用户,组,也可以使用主持人更新组。

我在网上找到的大多数解决方案似乎都使​​用apollo服务器或typeDefs。 而且结构与我的完全不同。 由于没有很多人以我的方式进行编码,所以我被困在这里。

因为我开始以这种方式进行编码,并且我觉得这种方式要简单得多,所以我坚持使用,而不是使用输入类型或为所有解析器创建文件。

我将文件夹和文件结构放在下面。

https://www.youtube.com/watch?v=Y0lDGjwRYKw&list=PL4cUxeGkcC9iK6Qhn-QLcXCXPQUov1U7f

这是我遵循的教程

我建立的关系。

// User
{
  firstName: String
  lastName: String
  facilitators: [Array of GroupID]
}

// Group
{
  name: String
  facilitators: [Array of UserId]
  member: [Array of UserId]
}

但是,我在检索数据时遇到了麻烦。 这是我的代码的问题。

name: "Group",
  fields: () => ({
    id: {type: GraphQLID},
    name: {type: GraphQLString},
    facilitators: {
      type: new GraphQLList(UserType),
      resolve(parent, args) {
    
         // THE SOLUTION COMES HERE...
    
      }
    },
  })

如果这是一对多的关系,我就能解决类似return User.find({ groupAsFacilitator: parent.id })的问题 在与主持人谈完后,我需要为成员做同样的逻辑。 我也在想这是否与猫鼬有关,而不是graphql ....

GraphQLObjectType

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => ({
    id: {type: GraphQLID},
    firstName: {type: GraphQLString},
    lastName: {type: GraphQLString},
    groupAsFacilitator: {
      type: new GraphQLList(GroupType),
      resolve(parent, args){
        return Group.find({ _id: parent.id });
      }
    },
    // groupAsMember
    createdAt: {type: GraphQLString},
  })
});

const GroupType = new GraphQLObjectType({
  name: "Group",
  fields: () => ({
    id: {type: GraphQLID},
    name: {type: GraphQLString},
    facilitators: {
      type: new GraphQLList(UserType),
      resolve(parent, args) {
        return User.find({ groupAsFacilitator: parent.id })
      }
    },
  })
});

RootQuery

module.exports = RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    user: {
      type: UserType,
      args: {id: {type: GraphQLID}},
      resolve(parent, args) {
        return User.findById(args.id);
      }
    },
    users: {
      type: new GraphQLList(UserType),
      resolve(parent, args) {
        return User.find({});
      }
    },
    group: {
      type: GroupType,
      args: {id: {type: GraphQLID}},
      resolve(parent, args) {
        return Group.findById(args.id);
      }
    },
    groups: {
      type: new GraphQLList(GroupType),
      resolve(parent, args) {
        return Group.find({});
      }
    },
  }
});

突变

module.exports = Mutation = new GraphQLObjectType({
  name: "Mutation",
  fields: {
    addUser: {
      type: UserType,
      args: {
        firstName: {type: new GraphQLNonNull(GraphQLString)},
        lastName: {type: new GraphQLNonNull(GraphQLString)},
      },
      resolve(parent, args) {
        const user = new User({
          firstName: args.firstName,
          lastName: args.lastName,
          groupAsFacilitator: [],
          // groupAsMember: [],
          createdAt: Date.now()
        });
        return user.save()
      }
    },
    addGroup: {
      type: GroupType,
      args: {
        name: {type: new GraphQLNonNull(GraphQLString)},
      },
      resolve(parent, args) {
        const group = new Group({
          name: args.name,
          facilitators: [],
          // members: [],
          createdAt: new Date()
        })
        return group.save();
      }
    },
    addGroupFacilitator: {
      type: GroupType,
      args: {
        groupId:{type: new GraphQLNonNull(GraphQLID)},
        facilitatorId: {type: new GraphQLNonNull(GraphQLID)},
      },
      async resolve(parent, args) {
        const group = await Group.findOne({ _id: args.groupId });
        const facilitator = await User.findOne({ _id: args.facilitatorId });

        if(group) {
          let facilitators = group.facilitators;
          facilitators.push(facilitator._id);
          await Group.updateOne({ _id: group._id }, { $set: { facilitators: facilitators } });
          return group;
        } else {
          throw new Error("Group with the given group ID not found");
        }
      }
    }
  }
});

文件夹和文件结构

C:.
│   .env
│   .gitignore
│   app.js
│
├───graphql
│   ├───query
│   │       Mutation.js
│   │       RootQuery.js
│   │
│   ├───schema
│   │       index.js
│   │
│   └───type
│           index.js
│
└───models
    │   index.js
    │
    └───models
            group.js
            user.js

如果有人知道,请告诉我如何解决此问题。 预先谢谢你。

0 个答案:

没有答案