Reputation: 952
Im new to GraphQL, JS and backend in general. Im trying to make a query to the BE demo im trying, but i cant get it to pass, i assume this is a syntax missunderstanding...
The func looks like:
Mutation: {
createUser: async (parent, { user }, context, info) => {
const newUser = await new User({
name: user.name,
email: user.email,
age: user.age
});
return new Promise((resolve, reject) => {
newUser.save((err, res) => {
err ? reject(err) : resolve(res);
});
});
},
and my query looks like:
mutation createUser(user: $user) {
name,
_id
}
with a var property of:
{
"user": {
"id": 1,
"name": "Jack"
}
}
my understanding would be that the mutation wants to take a user object, so i send the user query passing in the $user var?
Appreciate some help with what im not understanding here!
Upvotes: 0
Views: 106
Reputation: 1
Because I don' know about your schemas in detail, If you make your schema like this(email required, age required):
type User{
_id:ID!
name:String!
email:String!
age:Int!
}
then you should pass email, age info in your mutation parameter.
and seems like using mongoose. Then you can code like this:
Mutation: {
createUser: async (parent, { user }, context, info) => {
const newUser = await new User({
name: user.name,
email: user.email,
age: user.age
});
const result = newUser.save()
return {...result._doc, id:result.id}
},
Upvotes: 0
Reputation: 84707
What follows the mutation
keyword is the name for your operation, which is arbitrary and could even be omitted outright. You still need to actually identify which field or fields on the Mutation type you are querying. In this case, the field we want is createUser
, so we need to do something like this:
mutation SomeName ($user: UserInput) {
createUser(user: $user) {
name,
_id
}
}
Notice that we have to also define our variables in the first line. Then we can use those variables anywhere in our query. Also note that, based on your question, I have no idea what the type for $user
would actually be -- you'll need to change UserInput
to match your schema.
Upvotes: 1
Reputation: 5957
Would it be something like this:
Mutation: {
createUser(user, context, info) => {
const newUser = await new User({
name: user.name,
email: user.email
age: user.age
});
return Promise.resolve()
.then((data) => {
newUser.save(data);
})
.catch((err) => {
console.log(err);
});
});
}
Upvotes: 0