我在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()
的问题
1条答案
按热度按时间ddhy6vgd1#
您的问题只是在mongoose方面,您在
userSchema
中将type
定义为ObjectId
字符串
但是你要把一个
string
传递给你的突变:dept: {did: "1"…
个还请注意,将新ID作为从前端传递的突变参数可能是不好的做法-最好让MongoDB为您创建ID。最好使用
ObjectIds
而不是字符串作为主ID。