【问题标题】:Not able to write GraphQL Mutation for creating a new user in database无法编写用于在数据库中创建新用户的 GraphQL Mutation
【发布时间】:2018-02-17 09:39:49
【问题描述】:

我想做的基本上是将新用户插入数据库并使用 GraphQL Mutation 返回新用户数据。但我无法将数据插入到 数据库。在下图中获取空值而不是新的用户数据。谁能告诉我我的代码到底哪里错了。

schema.JS

type Mutation {
  createEmployee(input: EmployeeInput): Employee
}

input EmployeeInput {
    firstName: String
    lastName: String
    phone: String
    email: String
    name: String
    domainName: String
    smsID: String
}

type Employee {
    id: ID
    adminFirstName: String
    adminLastName: String
    adminPhone: String
    adminEmail: String
    smsID: String
    domainName: String
}

解析器.JS

import { employeesRepo } from "repos";

const mutationResolvers = {
    createEmployee: async ({ firstName, lastName, email, phone, businessName, domainName }) =>
    await employeesRepo.createEmployee(arguments[0])
};

employeesRepo.Js

async createEmployee(employee) {
let newEmployee = await this.employeeStore.insert(employee);
return newEmployee;

}

MongoStore.JS

async insert(document) {
   let db, collection, result, now;
   now = new Date();
   document.createdOn = now;
   document.lastUpdated = now;
   document._id = new ObjectId();
  try {
     db = await MongoClient.connect(url, options);
     collection = db.collection(this.collectionName);
     result = await collection.insertOne(document);
    } catch (err) {
      console.log(err);
    } finally {
     db.close();
   }
   return document;
  }

【问题讨论】:

    标签: javascript node.js mongodb graphql


    【解决方案1】:

    您已将解析器定义为:

    createEmployee: async (source) => await employeesRepo.createEmployee(source)
    

    但是,您实际上想要处理传递给该字段的 input 参数,该参数位于传递给 resolve 的第二个参数中。试试吧:

    createEmployee: async (source, args) => await employeesRepo.createEmployee(args.input)
    

    在此处查看GraphQLFieldResolveFn 的定义:

    http://graphql.org/graphql-js/type/#graphqlobjecttype

    type GraphQLFieldResolveFn = (
      source?: any,
      args?: {[argName: string]: any},
      context?: any,
      info?: GraphQLResolveInfo
    ) => any
    

    【讨论】:

    • 我在解析器函数中添加了 args,但仍然得到相同的输出。在我的代码中,我只是将字段传递给我的解析器函数。为什么我们需要 source 和 args。你能准确告诉我吗@Benjie
    • 传递给字段的参数在传递给解析的第二个参数中可用;即参数 [1] 或“参数”。您正在引用参数 [0](或“源”),它是父字段的解析值。
    猜你喜欢
    • 2018-11-10
    • 2020-09-27
    • 2019-06-02
    • 1970-01-01
    • 2012-10-27
    • 2020-10-02
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多