Search code examples
node.jsmongoosegraphqlgraphql-compose-mongoose

How to do a mutation with graphql and mongoose


I have a backend with mongoose, graphql and graphql-compose-mongoose.

I followed the graphql-compose-mongoose documentation to create a User model and schema as follows:

Model

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 Schema

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;

I wanna create a user with the userCreateOne mutation and I'm trying it out in the GraphQL playground. I can't seem to figure out how though. I've tried passing the field as arguments but it doesn't work.


Solution

  • I did figure it out in the end. The mutation looks like this:

    mutation {
      userCreateOne(record: {email: "[email protected]", password: "12345"}) {
        record {
          email
          password
          matchId
          created
          active
        }
      }
    }
    

    userCreateOne (and the mongoose resolver createOne) accept an object record and inside that object are the fields you defined in your schema.