[英]GraphQL Mongoose promise best practices
Using GraphiQL, I'm able to update a user with the following command (1). 使用GraphiQL,我可以使用以下命令(1)更新用户。 I'm able to return the actual user with the service (3). 我可以通过服务(3)返回实际用户。
Is there simpler/more compact way of returning the user after an update? 更新后有没有更简单/更紧凑的方式来返回用户? (seen how easy it is when creating a user). (可以看到创建用户时有多么容易)。
(1) GraphiQL mutation command mutation { updateUser(id: "1", firstName: "Bob"){ firstName } } (1)GraphiQL突变命令突变{updateUser(id:“ 1”,firstName:“ Bob”){firstName}}
(2) the mutation: (2)突变:
const mutation = new GraphQLObjectType({
updateUser: {
type: UserType,
args: {
id: { type: new GraphQLNonNull(GraphQLString) },
firstName: { type: GraphQLString },
age: { type: GraphQLInt },
companyId: { type: GraphQLString }
},
resolve(parentValue, args){
return UserService.updateUser(args);
}
},
})
(3) the service: (3)服务:
function updateUser(args) {
var {id} = args;
return User.findOne({id})
.then(user => {
if(!user){throw new Error('No user found')}
return User.update({id}, args)
.then(() => {
return User.findOne({id})
})
})
},
function addUser(args) {
const user = new User(args);
return user.save(args);
}
Assuming you're using mongoose
: 假设您使用mongoose
:
function updateUser(args) {
var {id} = args;
return await User.findOneAndUpdate({ id }, args, { new: true });
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.