16.5. Creating a CRUD with NodeJS and MongoDB: Connecting to the MongoDB database

Página 89

16.5. Creating a CRUD with NodeJS and MongoDB: Connecting to the MongoDB Database

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.

Now answer the exercise about the content:

What is Mongoose in the context of NodeJS and MongoDB development?

You are right! Congratulations, now go to the next page

You missed! Try again.

Next page of the Free Ebook:

9016.6. Creating a CRUD with NodeJS and MongoDB: Creating routes for the CRUD

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text