DEV Community

Cover image for MongoDB and the Mongoose
Connor Schratz
Connor Schratz

Posted on

MongoDB and the Mongoose

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

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

> sudo apt-get install -y mongodb-org
Enter fullscreen mode Exit fullscreen mode

Once that install completes, enter the following command into your terminal.

> sudo service mongodb
Enter fullscreen mode Exit fullscreen mode

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

> Usage: /etc/init.d/mongodb {start|stop|force-stop|restart|force-reload|status} 
Enter fullscreen mode Exit fullscreen mode

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

> sudo service mongodb start
Enter fullscreen mode Exit fullscreen mode

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

> Starting database mongodb 
Enter fullscreen mode Exit fullscreen mode

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

> mongo
Enter fullscreen mode Exit fullscreen mode

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.

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

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

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));
Enter fullscreen mode Exit fullscreen mode

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.

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

const Article = mongoose.model('Article', articleSchema);
Enter fullscreen mode Exit fullscreen mode

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.

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

newArticle.save();
Enter fullscreen mode Exit fullscreen mode

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!

Article.find()
  .then(articles => console.log(articles))
  .catch(err => console.log('Error: ', err));
Enter fullscreen mode Exit fullscreen mode

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:

{ 
 _id: 79e8tebf696e5n89y92hf654u
 title: 'Javascript 101',
 author: 'Connor',
 pages: 3
}
Enter fullscreen mode Exit fullscreen mode

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.

Article.findOneAndDelete({title: 'Javascript 101' }))
  .then(() => {
    console.log('Entry deleted!');
  })
  .catch((err) => {
    console.log('Error: ', err);
  });
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)