javascript - 无法编写 GraphQL Mutation 来在数据库中创建新用户

标签 javascript node.js mongodb graphql

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

架构.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;
  }

最佳答案

您已将解析器定义为:

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

关于javascript - 无法编写 GraphQL Mutation 来在数据库中创建新用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116859/

相关文章:

javascript - ObjectID 不存储十六进制值

node.js - kafka-node 几个消费者

javascript - 使用 node.js 写入 MongoDB 副本集

mongodb - 关于 Redux 中的规范化

javascript - 过期后设置字段(MongoDB)

javascript - 在Gojs中编辑滚动表行中的任何文本时如何获取行值?

javascript - 为什么我在调用 OnSubmit 时必须返回我的函数的返回值?

javascript - angular-ui-tabset:更改事件选项卡内容

javascript - 如何在按钮内使用选择?

node.js - 如何从 NodeJS Lambda 函数中的 axios.get 等异步函数获取返回值?