Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4) by pckurdu

View this thread on steempeak.com
· @pckurdu ·
$20.03
Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)
![graphql.fw.png](https://cdn.steemitimages.com/DQmPTUWQy5MFkJ7okpZ2eAq4Aevp5fLwGqghrVfTFdfkjn6/graphql.fw.png)
# Repository

### React
https://github.com/facebook/react

### Graphql
https://github.com/graphql/graphql-js

### Apollo
https://github.com/apollographql/apollo-client

### Express
https://github.com/expressjs/express

### My Github Address
https://github.com/pckurdu

### This Project Github Address
https://github.com/pckurdu/Build-A-Library-Application-With-Graphql-ExpressJs-React-Apollo-and-MongoDB-Part-4

# What Will I Learn?

- You will learn how to create a database and database user on mlab.
- You will learn how to make mlab connection with graphql application.
- You will learn how to use Mongoose packages.
- You will learn the concept of mutation in Graphql.
- You will learn how to add data to the mongoDB database with Graphql mutation.

# Requirements

- text editor (I used visual studio code editor)
- Basic javascript information
- Basic react information

# Difficulty

- Basic

# Tutorial Contents

Hello to everyone.

In this tutorial, we will contact the library application with `mLab`, the cloud system of the mongodb database. 

We will create a database using mLab and add users to this database for use in the application.We will install mongoose packages after making the connection. We will produce mongoose models to access the database from the application and send the book and author data to the database with the help of these models.

We will use mutation types in graphql and we will add the authors to the database with mutation. So we will add our first data to the mongodb database with GraphiQL

I have divided this tutorial into sections as follows:

- Make A mLab Connection
- Mongoose Model Creation
- Adding Authors With Mutation

### 1- Make A mLab Connection

We are ready to connect mLab with our library application. In this section we will talk about what `mLab` is and build a database on mLab. We will also connect the database we created on mLab with the application.

`mLab` is a cloud system that provides `mongoDB` database online and provides the necessary transactions automatically. In fact mLab is a mongoDb that we can use anywhere on the internet and not on local devices.

In order to use mLab in our application, we must first enter the mLab website and become a member. After signing up, we can use the mLab tools and perform database operations.

![graphql1.gif](https://cdn.steemitimages.com/DQmYK9FvnmYbRZ8FN6hQ1431QCPWJcYe1xWpMMu6TweFhQx/graphql1.gif)

We can create the database after performing the membership process. The following gif shows how to create a database.

![graphql2.gif](https://cdn.steemitimages.com/DQmSrDmmtSDrapY8WtYdmg2XQYBBjC72HkKdsbHaHtY2VnX/graphql2.gif)

After creating the database, we need to define user in order to use this database. We will identify this user's information within the application and link the application to the database.

![graphql3.gif](https://cdn.steemitimages.com/DQmRicrT1rBuUvhvzzbh3kFo3M5vVcC4ce3ezsNCX6PjC2b/graphql3.gif)

Now that we have created a database and a user, we can proceed to the application process. In order to use mongoDB tools in the application, we must use `mongoose` packages.

First download these `mongoose` packages for use in the application. Here we have to remember that we need to download mongoose packages into the server folder.

```
npm install mongoose
```
<br>
After downloading the packages, we need to enable mongoose in the `app.js` file.
```
//for mongoose packages
const mongoose=require('mongoose');
```
<br>
We will connect to the database using the `connect()` function. The connect () function allows us to check whether there are permissions required to connect to the database. We need to use the information of the user we created here.
```
//generated user information is used.
mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds139037.mlab.com:39037/pckurdu');
```
<br>
You must type the user name that you created in the `dbuser` field and the user's password in the `dbpassword` field.
If the entered values are correct, we can now make the connection. Using `connection.once ()`, let's manage the connection and print the mLab connection to the console for success.
```
//Connecting with mLab.
mongoose.connection.once('open',()=>{
    console.log('mLab conncetion success');
})
```
<br>
Console picture is as follows

![graphql1.png](https://cdn.steemitimages.com/DQmcAaVc1e5pFkj5FM53FDPUpjXGTWd8BkKPxLWVibfGmn2/graphql1.png)
<br>
### 2- Mongoose Model Creation

Now that we have created the database we can create models that we will use.

In this section we will create book and author models for the library application using mongoose. We will perform database operations with these models and we will not need the fake data we have created because we will bring the book and author data from the database we created in mLab.

Let's create a separate folder to create mongoose models. We will create a folder named `models` under the server folder and create the `author.js` and `book.js` files under the models folder.

![graphql2.png](https://cdn.steemitimages.com/DQmY5DGmMtZQHpiCQwd33BoitERsMf2HXsgNy5Bt8SLUntv/graphql2.png)

We can now create our models. Let's create the book model.

#### In models>book.js
```

//for mongoose tools
const mongoose=require('mongoose');

//for create mongoose schema
const Schema=mongoose.Schema;

//create schema
const bookSchema=new Schema({

    name:String,
    type:String,
    authorId:String
});

//export the schema
module.exports=mongoose.model('Book',bookSchema);
```
<br>
We should use `Schema` to create mongoose model with schema, we can set which fields to use in the model. We need the name of the book, the type of book, and the authorId of the book to create a book model, we set them as a string.
After creating schema, we need to export this schema to use it as a model. We can export using the `model()` function in mongoose.

Let's do the same in the author and create the author model.
```
//for mongoose tools
const mongoose=require('mongoose');

//for create mongoose schema
const Schema=mongoose.Schema;

//create schema
const authorSchema=new Schema({

    name:String,
    age:Number,
});

//export the schema
module.exports=mongoose.model('Author',authorSchema);
```
<br>
So we created models and we don't need fake data because we'll access the data using the model.

Then let's delete all the fake data we have created. We can no longer access fake data using lodash because we have deleted the fake data. Since we will use a model, delete all lodash functions.

After performing deletions, let us define the models we created in `schema.js` file.
```
//models
const Book=require('../models/book');
const Author=require('../models/author');
```
<br>
### 3- Adding Authors With Mutation

In this section, we will create `mutation` and and add authors to the database with mutation. So what is this mutation?

We use mutation structure in graphql to add, update and delete data. Let's create one mutation and write the code for the adding author process.

#### In schema.js
```
//Creating a mutation using GraphQLObjectType
const Mutation=new GraphQLObjectType({

});
```
<br>
We use `GraphQLObjectType` to create the mutation. In order for our query to see this type as mutation, we must enter the name we defined in the mutation field when exporting the schema.
```
//we export the schema with root query.
module.exports=new GraphQLSchema({
    query:RootQuery,
    mutation:Mutation
});
```
<br>
Thus we have created the first mutation. What we need to do now is to define the area we want this mutation to do.
```
//Creating a mutation using GraphQLObjectType
const Mutation=new GraphQLObjectType({
    name:'Mutation',
    fields:{
        //field required to add author
        addAuthor:{
            //author add operations
        }
    }
});
```
<br>
In the addAuthor field, we must set the fields that we will make changes using the author type.
```
//field required to add author
addAuthor:{
   //author add operations
   type:authorType,
   args:{
      name:{type:GraphQLString},
      age:{type:GraphQLInt}
  },
  resolve(parent,args){
  //mongoDB codes
  }
}
```
<br>
We can access the author's fields using the args field we created. When we create the author object to add to the mongodb field and run the author.save () command, we add the author to the database.
```
resolve(parent,args){
  //mongoDB codes
  let author=new Author({
    name:args.name,
    age:args.age
});
   return author.save();
}
```
<br>
Then let's test the mutation field and add the first author.

The GraphiQL field now includes the mutation field in the schema

![graphql4.gif](https://cdn.steemitimages.com/DQmYg65ppiDTRBGvpMLFZbZRZh2HSqKm5uxGFcnFnfi2SJc/graphql4.gif)

Let's add author using mutation in GraphiQL field.

![graphql5.gif](https://cdn.steemitimages.com/DQmeciea9bRudhjhu98tAJZQuNiGrV9SkZ5HYggdqLKnoyD/graphql5.gif)

Now we have added our first author. Let's look at the mLab page.
![graphql6.gif](https://cdn.steemitimages.com/DQmd22yx8zBHR1WoAb6feAcbsZUWNyhcwPaCZHQ5kzVG1NP/graphql6.gif)

# Curriculum

<a href="https://steemit.com/utopian-io/@pckurdu/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-1">Part 1</a> - <a href="https://steemit.com/utopian-io/@pckurdu/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-2">Part 2</a> - <a href="https://steemit.com/utopian-io/@pckurdu/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-3">Part 3</a>

# Proof of Work Done

https://github.com/pckurdu/Build-A-Library-Application-With-Graphql-ExpressJs-React-Apollo-and-MongoDB-Part-4
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 403 others
properties (23)
post_id76,577,965
authorpckurdu
permlinkbuild-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-4
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","graphql","react","mongodb"],"image":["https:\/\/cdn.steemitimages.com\/DQmPTUWQy5MFkJ7okpZ2eAq4Aevp5fLwGqghrVfTFdfkjn6\/graphql.fw.png","https:\/\/cdn.steemitimages.com\/DQmYK9FvnmYbRZ8FN6hQ1431QCPWJcYe1xWpMMu6TweFhQx\/graphql1.gif","https:\/\/cdn.steemitimages.com\/DQmSrDmmtSDrapY8WtYdmg2XQYBBjC72HkKdsbHaHtY2VnX\/graphql2.gif","https:\/\/cdn.steemitimages.com\/DQmRicrT1rBuUvhvzzbh3kFo3M5vVcC4ce3ezsNCX6PjC2b\/graphql3.gif","https:\/\/cdn.steemitimages.com\/DQmcAaVc1e5pFkj5FM53FDPUpjXGTWd8BkKPxLWVibfGmn2\/graphql1.png","https:\/\/cdn.steemitimages.com\/DQmY5DGmMtZQHpiCQwd33BoitERsMf2HXsgNy5Bt8SLUntv\/graphql2.png","https:\/\/cdn.steemitimages.com\/DQmYg65ppiDTRBGvpMLFZbZRZh2HSqKm5uxGFcnFnfi2SJc\/graphql4.gif","https:\/\/cdn.steemitimages.com\/DQmeciea9bRudhjhu98tAJZQuNiGrV9SkZ5HYggdqLKnoyD\/graphql5.gif","https:\/\/cdn.steemitimages.com\/DQmd22yx8zBHR1WoAb6feAcbsZUWNyhcwPaCZHQ5kzVG1NP\/graphql6.gif"],"links":["https:\/\/github.com\/facebook\/react","https:\/\/github.com\/graphql\/graphql-js","https:\/\/github.com\/apollographql\/apollo-client","https:\/\/github.com\/expressjs\/express","https:\/\/github.com\/pckurdu","https:\/\/github.com\/pckurdu\/Build-A-Library-Application-With-Graphql-ExpressJs-React-Apollo-and-MongoDB-Part-4","https:\/\/steemit.com\/utopian-io\/@pckurdu\/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-1","https:\/\/steemit.com\/utopian-io\/@pckurdu\/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-2","https:\/\/steemit.com\/utopian-io\/@pckurdu\/build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-3"],"app":"steemit\/0.1","format":"markdown"}
created2019-06-18 06:27:45
last_update2019-06-18 06:27:45
depth0
children5
net_rshares34,172,210,190,735
last_payout2019-06-25 06:27:45
cashout_time1969-12-31 23:59:59
total_payout_value15.227 SBD
curator_payout_value4.799 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length9,745
author_reputation23,382,389,405,576
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (467)
@portugalcoin ·
$11.33
Thank you for your contribution @pckurdu.
After reviewing your tutorial we suggest the following points listed below:

- Excellent tutorial, very well structured and explained. Good job!

- Using GIFs to show results is definitely better than standard still images.

- Thanks for following our suggestions we gave in previous tutorials.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/2-1-1-1-1-3-1-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id76,616,837
authorportugalcoin
permlinkptb9ix
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["pckurdu"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/2-1-1-1-1-3-1-3-","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"],"app":"steemit\/0.1"}
created2019-06-18 20:13:45
last_update2019-06-18 20:13:45
depth1
children1
net_rshares19,463,891,312,343
last_payout2019-06-25 20:13:45
cashout_time1969-12-31 23:59:59
total_payout_value8.616 SBD
curator_payout_value2.715 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length833
author_reputation214,343,891,436,406
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (27)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id76,763,065
authorutopian-io
permlinkre-ptb9ix-20190621t063056z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-06-21 06:30:57
last_update2019-06-21 06:30:57
depth2
children0
net_rshares0
last_payout2019-06-28 06:30:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length64
author_reputation152,913,012,544,965
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-ua ·
#### Hi @pckurdu!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
post_id76,616,999
authorsteem-ua
permlinkre-build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-4-20190618t201631z
categoryutopian-io
json_metadata{"app":"beem\/0.20.19"}
created2019-06-18 20:16:33
last_update2019-06-18 20:16:33
depth1
children0
net_rshares0
last_payout2019-06-25 20:16:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length286
author_reputation23,203,609,903,979
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
Hey, @pckurdu!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id76,619,605
authorutopian-io
permlinkre-build-a-library-application-with-graphql-expressjs-react-apollo-and-mongodb-part-4-20190618t210635z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-06-18 21:06:36
last_update2019-06-18 21:06:36
depth1
children0
net_rshares0
last_payout2019-06-25 21:06:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length589
author_reputation152,913,012,544,965
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@surpassinggoogle ·
Hi bro, I have some tasks related to vue and react all on Github and utopian approved. Can you help me with some? I have some steem bounty too and the bounty isn’t big as I am really short on funds but I will love to tip additional steem especially where contributions are timely. I really need help basically.

Here is a list:

https://steemit.com/utopian-io/@surpassinggoogle/in-dire-need-of-help-are-you-ready-to-make-your-picks-1500-steem-and-20-000-teardrops-shared-among-a-collection-of-development

Most of the assigned tasks havent really been taken yet as those who were assigned became unavailable.

The projects are steemgigs.org and ulogs.org
properties (22)
post_id76,630,621
authorsurpassinggoogle
permlinkptbnjt
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https:\/\/steemit.com\/utopian-io\/@surpassinggoogle\/in-dire-need-of-help-are-you-ready-to-make-your-picks-1500-steem-and-20-000-teardrops-shared-among-a-collection-of-development"],"app":"steemit\/0.1"}
created2019-06-19 01:16:42
last_update2019-06-19 01:16:42
depth1
children0
net_rshares0
last_payout2019-06-26 01:16:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length654
author_reputation508,940,095,151,809
root_title"Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 4)"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000