如何使用 graphql 和 mongoose 进行突变

How to do a mutation with graphql and mongoose

我有一个后端 mongoosegraphqlgraphql-compose-mongoose

我按照 graphql-compose-mongoose documentation 创建了一个用户模型和架构,如下所示:

型号

import mongoose, { Schema } from 'mongoose';
import { composeMongoose } from 'graphql-compose-mongoose';

export const UserSchema = new Schema({
    phone: { type: String },
    name: { type: String },
    email:    { type: String, required: true },
    password: { type: String, required: true },

    photos: { type: Array },
    matchId: { type: Schema.Types.ObjectId },

    created: { type: Date, default: Date.now },
    active: { type: Boolean, default: false }
});

export const User = mongoose.model('User', UserSchema);
export const UserTC = composeMongoose(User);

Graphql 架构

import { User, UserTC } from '../models/User';
import { schemaComposer } from 'graphql-compose';

schemaComposer.Query.addFields({
  userById: UserTC.mongooseResolvers.findById(),
  userByIds: UserTC.mongooseResolvers.findByIds(),
  userOne: UserTC.mongooseResolvers.findOne(),
  userMany: UserTC.mongooseResolvers.findMany(),
  userDataLoader: UserTC.mongooseResolvers.dataLoader(),
  userDataLoaderMany: UserTC.mongooseResolvers.dataLoaderMany(),
  userCount: UserTC.mongooseResolvers.count(),
  userConnection: UserTC.mongooseResolvers.connection(),
  userPagination: UserTC.mongooseResolvers.pagination()
});

schemaComposer.Mutation.addFields({
  userCreateOne: UserTC.mongooseResolvers.createOne(),
  userCreateMany: UserTC.mongooseResolvers.createMany(),
  userUpdateById: UserTC.mongooseResolvers.updateById(),
  userUpdateOne: UserTC.mongooseResolvers.updateOne(),
  userUpdateMany: UserTC.mongooseResolvers.updateMany(),
  userRemoveById: UserTC.mongooseResolvers.removeById(),
  userRemoveOne: UserTC.mongooseResolvers.removeOne(),
  userRemoveMany: UserTC.mongooseResolvers.removeMany()
});

const graphqlSchema = schemaComposer.buildSchema();

export default graphqlSchema;

我想创建一个具有 userCreateOne 突变的用户,我正在 GraphQL 操场上尝试一下。我似乎无法弄清楚如何。我试过将字段作为参数传递,但它不起作用。

最后我确实弄明白了。突变看起来像这样:

mutation {
  userCreateOne(record: {email: "email@example.com", password: "12345"}) {
    record {
      email
      password
      matchId
      created
      active
    }
  }
}

userCreateOne(和 mongoose 解析器 createOne)接受一个对象 record 并且该对象内部是您在模式中定义的字段。