[英]Get data of new dataset, which is created via GraphQL mutation
我正在尝试做一个突变。 突变本身正在起作用(用户是在数据库中创建的),但是响应仅具有null
值:
data
createUser:
createdAt: null
password: null
username: null
我看不到我在做什么错。 我想我必须指定我想取回哪些数据。 但是在创建用户时,我不知道其ID。 那么,如何获取当前添加的数据集作为响应?
服务器/突变模式
const UserType = new GraphQLObjectType({
name: 'user',
fields: {
_id: { type: GraphQLID },
createdAt: { type: GraphQLString },
username: { type: GraphQLString },
password: { type: GraphQLString }
}
})
const MutationType = new GraphQLObjectType({
name: 'RootMutationType',
description: 'Mutations',
fields: () => ({
createUser: {
type: UserType,
args: {
username: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) }
},
async resolve ({ db }, { username, password }) {
return db.collection('users').insert({
_id: Random.id(),
createdAt: new Date(),
username,
password: bcrypt.hashSync(password, 10)
})
}
}
})
})
客户/组件
this.props.createUserMutation({
variables: { username, password }
}).then(response => {
console.log(response.data) // data has expected fields, but those have null value
})
// ...
export default compose(
withData,
withApollo,
graphql(
gql`
mutation RootMutationQuery($username: String!, $password: String!) {
createUser(
username: $username,
password: $password,
) {
_id
createdAt
username
password
}
}
`, {
name: 'createUserMutation'
}
)
)
我认为应该知道发生了什么错误
所以改变这个查询
this.props.createUserMutation({ variables: { username, password } }).then(response => { console.log(response.data) // data has expected fields, but those have null value })
至
this.props.createUserMutation({ variables: { username, password } }).then(response => { console.log(response.data) // data has expected fields, but those have null value }).catch(error => { console.error(error) })
我没有使用过流星,但查看文档,我认为您的insert调用仅返回id,并且实际的db操作是异步完成的。
在这种情况下,您需要在发送插入调用之前确定_id
和createAt
的值,因此您拥有将其发送回客户端的所有信息。 做就是了:
resolve ({ db }, { username, password }) {
const _id = Random.id()
const createdAt = new Date()
db.collection('users').insert({
_id,
createdAt,
username,
password: bcrypt.hashSync(password, 10)
})
return { _id, username, password, createdAt }
}
如果我们希望MongoDB为我们生成_id,则可以从插入调用中将其忽略:
resolve ({ db }, { username, password }) {
const createdAt = new Date()
const _id = db.collection('users').insert({
createdAt,
username,
password: bcrypt.hashSync(password, 10)
})
return { _id, username, password, createdAt }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.