16.5. Creating a CRUD with NodeJS and MongoDB: Connecting to the MongoDB Database
In this section of our e-book, we'll cover one of the most important aspects of developing APIs in NodeJS: creating a CRUD (Create, Read, Update, Delete) with NodeJS and MongoDB. This is a crucial step for any developer wanting to build robust, scalable applications.
Connection to MongoDB database
Before we start creating our CRUD, we need to establish a connection to the MongoDB database. There are several ways to do this, but one of the most common is to use the Mongoose package, which is an ODM (Object Data Modeling) for MongoDB and Node.js.
To install Mongoose, you can use npm (Node Package Manager) with the following command:
npm install mongoose
Once installed, you can start using it to connect to MongoDB. Here is an example of how to do this:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
This code connects to a local instance of MongoDB running on your computer. If you are using a hosted MongoDB database service such as MongoDB Atlas, you will need to replace 'mongodb://localhost/test' with the connection URL provided by your hosting service.
Creating a CRUD with NodeJS and MongoDB
Once we have our connection to MongoDB established, we can start creating our CRUD. To do this, we first need to define a schema for our data. In Mongoose, a schema is a structure that defines the form of documents within a MongoDB collection.
Here is an example of how you can define a schema for a blog post:
const blogSchema = new mongoose.Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
goal: {
votes: Number,
favs: Number
}
});
Once we have our schema defined, we can create a template from it. A model is a class with which we build documents. In the following example, we create a 'Blog' model from our 'blogSchema' schema:
const Blog = mongoose.model('Blog', blogSchema);
With our template in hand, we can start creating, reading, updating, and deleting documents. Here is an example of how you can create a new document using our 'Blog' template:
const blogPost = new Blog({ title: 'My First Post', author: 'John Doe', body: 'This is my first blog post.' });
blogPost.save(function (err, blogPost) {
if (err) return console.error(err);
console.log(blogPost.title + " saved to blog collection.");
});
To read documents, you can use the 'find' method. Here's an example of how you can find all blog posts by a given author:
Blog.find({ author: 'John Doe' }, function(err, blogs) {
if (err) return console.error(err);
console.log(blogs);
});
To update a document, you can use the 'updateOne' method. Here is an example of how you can update the title of a blog post:
Blog.updateOne({ title: 'My First Post' }, { title: 'My Updated Post' }, function(err, res) {
if (err) return console.error(err);
console.log(res);
});
Finally, to delete a document, you can use the 'deleteOne' method. Here is an example of how you can delete a blog post:
Blog.deleteOne({ title: 'My Updated Post' }, function(err) {
if (err) return console.error(err);
console.log('Post deleted');
});
With that, we conclude our introduction to creating a CRUD with NodeJS and MongoDB. In the next chapter, we'll explore each of these operations in more detail and learn how to handle errors and validate data.