Refer here for Part 1
While using graphql in express, we add the schema and resolvers to set the graphql middleware. Here, we'll be adding a new user to mongo for which we've already created a schema file
./models/user.js
const mongoose=require('mongoose')
const userSchema= new mongoose.Schema({
email:{
type:String,
required:true
},
password:{
type:String,
required:true
}
})
module.exports=mongoose.model("user",userSchema)
Import the user schema to your server
const User=require("./models/user")
Since, we are performing one of the CRUD operations, let's add the addUser mutation in our code.
type RootMutation{
addUser(userInput:UserInput!):User!
}
Let's go ahead and create the User types and User input
type User{
_id:ID!,
email:String!,
password:String!
}
input UserInput{
email:String!,
password:String!
}
As we call the addUser mutation, a corresponding resolver is required to perform the subsequent task of adding the user to database. rootValue denotes the resolver functions.
rootValue: {
addUser:async (args)=>{
try{
const user=new User({
email:args.userInput.email,
password:args.userInput.password
})
const result=await user.save()
console.log("result:"+result)
return{
...result._doc
}
}
catch(err){
console.log(err)
}
}
}
Since we are returning a user on every new user creation, we need to create a new object and set the newly created user's properties to it. We are using async await to cater to asynchronous calls.
In the end, we need to save the user to the db, hence we call user.save()
Let's test it in our playground
Check your database and you'll see the new user entry
Let's add the user query and corresponding resolver and check the result
type RootQuery{
user(id:ID!):User!
}
user: async(args) => {
try{
const user=await User.findOne({_id:args.id})
return{
...user._doc
}
}
catch(err){
throw err
}
}
Top comments (0)