MongoDB and the Mongoose
Published: 2020-07-27 06:23:24

There are a variety of great databases available to web developers. If you prefer a RDBMS such as MySQL, well that's just dandy and I commend you for using it! If you're not the biggest fan of MySQL, you might enjoy using MongoDB. MongoDB is considered a NoSQL database meaning it does not use relations to define the data within it. Instead MongoDB stores its data in a format similar to that of JSON, which makes it a lot easier to work with. Let's take a look at how you can create and interact with a MongoDB database. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dpk8lfw4rocqtpmip4b3.png)

## Setting up MongoDB

First thing you need to do is install MongoDB. This post will cover the process on Ubuntu. First run this command in your terminal 

```javascript 
> sudo apt-get install -y mongodb-org
```
Once that install completes, enter the following command into your terminal. 

```javascript 
> sudo service mongodb
```

This will provide you with the following print out in the terminal. 

```javascript
> Usage: /etc/init.d/mongodb {start|stop|force-stop|restart|force-reload|status} 
```

Those are the options that are available to the MongoDB service. In order to start your MongoDB database, just run the following command. 

```javascript 
> sudo service mongodb start
```

You should expect to see the following printed to the terminal. 

```javascript
> Starting database mongodb 
```

Once the database has started you can open the MongoDB terminal using the following command. 

```javascript 
> mongo
```
You should be able to see the MongoDB terminal, once you made it here, you're done with the setup, now let's look at how to create and add data using Mongoose. 

##Mongoose
Mongoose is an object data modeling or ODM for MongoDB. It allows us to take care of creating, reading, updating, and deleting data within our MongoDB database. Using Mongoose makes managing the data in your database, really easy. Let's get Mongoose set up, and add some data to the database. 

First you'll need to install Mongoose using npm or Node Packet Manager. Run the following command to set up Mongoose in your project. 

```javascript
npm install mongoose
```
Once Mongoose is installed you're ready to create your database. Let's take a look at that process. 

```javascript 
const mongoose = require('mongoose');

const db = mongoose.connect('mongodb://localhost/mediumdb', { useNewUrlParser: true })
  .then(() => console.log('Connected to database'))
  .catch(err => console.error('Connection failed', err));
```
As you can see from this example, Mongoose is promise based, making it really great at handling incoming response from the database, no more pesky callbacks!

The next important step is to create a schema for your database, Mongoose makes this process extremely easy, let's create our schema. 

```javascript
const articleSchema = new mongoose.Schema({
  title: { type: String, unique: true },
  author: String
  pages: Number
});

const Article = mongoose.model('Article', articleSchema);
```
It's as easy as that, now we've created the schema for our database entries and created a model from it. Mongoose models have a lot of great built in methods that are easy to use. Let's look at how we'd create a new entry in the database using the Article model. 

```javascript 
cosnt newArticle = new Article({
   title: 'Javascript 101', 
   author: 'Connor', 
   pages: 3
 });

newArticle.save();
```
There we go, now we've created a new entry in the database. It's important to remember that every new entry that is created this way, must also be saved using the .save() method, if you don't call that your entry won't be saved! 

Now let's take a look at how we've query the database for our entry. It's rather easy! 

```javascript
Article.find()
  .then(articles => console.log(articles))
  .catch(err => console.log('Error: ', err));
``` 
Boom! Just like that we have access to all of the article entries in the database, the response from the database will look like this:

```javascript 
{ 
 _id: 79e8tebf696e5n89y92hf654u
 title: 'Javascript 101',
 author: 'Connor',
 pages: 3
}
```
Notice how MongoDB automatically gives each entry a unique _id, which is great for keeping track of entries in the database especially if it's one that contains user information. Mongoose also allow us the ability to delete specific entries in the database.

```javascript 
Article.findOneAndDelete({title: 'Javascript 101' }))
  .then(() => {
    console.log('Entry deleted!');
  })
  .catch((err) => {
    console.log('Error: ', err);
  });
```
Just like that, our Javascript 101 article entry is deleted and our database is now empty, but not to worry we can still add plenty of other articles to the database whenever we want. 

##Conclusion
MongoDB is great database option when you need to store data in a way that is very similar to Javascript objects. It allows us as programmers to use a syntax that we're very familiar with and thus decrease the likelihood of introducing bugs and errors into our code. I hope this article has provided some insight on how to get started with MongoDB and Mongoose, now get out there and put this knowledge to use in your own code!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g5kupp5vzvr3ruoqlhv2.png)