1

I have this db_schema in Mongoose:

const userSchema = new Schema({
    uid: {
        type: String,
        required: true,
        unique: true,
    },
    name: {
        type: String,
        required: true,
    },
    dept: {
        type: Schema.Types.ObjectId,
        ref: 'Dept',
        required: true,
    },
});

const deptSchema = new Schema({
    did: {
        type: String,
        required: true,
        unique: true,
    },
    name: {
        type: String,
        required: true,
    },
});

const User = model('User', userSchema);
const Dept = model('Dept', deptSchema);

export { User, Dept };

and in GraphQL I have this schema:

type User {
  uid: String!
  name: String!
  dept: Dept!
}

type Dept {
  did: String!
  name: String!
}

input DeptInput {
  did: String!,
  name: String!
}


type Mutation {
  createUser(uid: String!, name: String!, dept: DeptInput): User     
}

in the resolver, I do:

Mutation: {
  createUser: async(_, { uid, name, dept }) => {
    try {

      // Create the new user
      const newUser = new User({ uid, name, dept: { did: dept.did, name: dept.name } });
      await newUser.save();

      return newUser;
    } catch (error) {
      throw new Error('Failed to create user');
    }
  }
}

when I try this in the playground:

mutation {
  createUser(uid: "5", name: "osama alatraqchi", dept: {did: "1", name: "CS"}) {
    name uid dept {did name}
  }
}

I get this error :

 "Failed to create user: Cast to ObjectId failed for value \"1\"
 (type string) at path \"_id\" for model \"Dept\""

Note: everything is working correctly, just the problem with createUser()

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61

1 Answers1

0

Your problem is just on the mongoose side, you've got type defined as an ObjectId in your userSchema

dept: {
        type: Schema.Types.ObjectId, <<<
        ref: 'Dept',
        required: true,
    },
});

But then you're passing in a string to your mutation: dept: {did: "1"…

Note also that it can be bad practice for new IDs to be mutation parameters that are passed from the front end - best to let MongoDB create IDs for you. Also best to use ObjectIds instead of strings as primary IDs.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39