Apollo服务器中mongoose和GraphQL模式的关系

mwkjh3gx  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(133)

我在Mongoose中有这个db_schema:

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 };

字符串
在GraphQL中,我有这样的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     
}


在解析器中,我:

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');
    }
  }
}


当我在操场上试着这么做时

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


我得到这个错误:

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


注意:一切都正常工作,只是createUser()的问题

ddhy6vgd

ddhy6vgd1#

您的问题只是在mongoose方面,您在userSchema中将type定义为ObjectId

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

字符串
但是你要把一个string传递给你的突变:dept: {did: "1"…
还请注意,将新ID作为从前端传递的突变参数可能是不好的做法-最好让MongoDB为您创建ID。最好使用ObjectIds而不是字符串作为主ID。

相关问题