15. Integrating NodeJS with MongoDB

Página 83

Integrating NodeJS with MongoDB is an essential step in developing robust and scalable APIs. MongoDB is a document-based NoSQL database that offers high performance, high availability, and easy scalability. It works well with NodeJS, providing an efficient way to manage and manipulate data.

1. MongoDB Installation

Before we start integrating MongoDB with NodeJS, we need to make sure that MongoDB is installed on our system. If you haven't installed it yet, you can download it from the official MongoDB website. After installation, you can start MongoDB in a separate terminal and leave it running in the background.

2. Configuring Mongoose

Mongoose is a NodeJS library that provides a straightforward, schema-based solution for modeling your application's data. It provides an easy way to connect our NodeJS application to MongoDB. To install Mongoose, you can use npm (Node Package Manager) with the following command: npm install mongoose.

Once installed, we need to configure it to connect to our 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 will connect your NodeJS application to the MongoDB database named 'test' that is running locally on your machine. The useNewUrlParser and useUnifiedTopology options are just to avoid deprecation warnings.

3. Creating Templates

With Mongoose, we can define what we call 'Models' for our data. A model is a class with which we build documents. In other words, models are like blueprints for our data. Here is an example of how to define a template:

const Schema = mongoose.Schema;

const blogSchema = new 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
  }
});

const Blog = mongoose.model('Blog', blogSchema);

In this example, we create a template for a blog. Each blog will have a title, author, body, a list of comments, a date, a hidden boolean, and some metadata. Each of these fields has a specific type associated with it.

4. Creating and Reading Documents

Once we have our template, we can start creating documents. Here is an example of how to create a new document:

const myBlog = new Blog({ title: 'My First Blog', author: 'John Doe', body: 'Hello, world!' });
myBlog.save(function (err, myBlog) {
  if (err) return console.error(err);
  console.log('Blog saved successfully!');
});

To read documents, we can use the find() method in our model:

Blog.find({ author: 'John Doe' }, function(err, blogs) {
  if (err) return console.error(err);
  console.log(blogs);
});

5. Updating and Deleting Documents

Mongoose also provides methods for updating and deleting documents. Here is an example of how to update a document:

Blog.updateOne({ author: 'John Doe' }, { title: 'Updated Blog Title' }, function(err, res) {
  if (err) return console.error(err);
  console.log(res);
});

And here is an example of how to delete a document:

Blog.deleteOne({ author: 'John Doe' }, function(err) {
  if (err) return console.error(err);
  console.log('Blog deleted successfully!');
});

Integrating NodeJS with MongoDB is a relatively simple but powerful task. With the ability to create, read, update, and delete documents, you can build robust, scalable APIs that can efficiently handle large amounts of data.

Now answer the exercise about the content:

What is Mongoose's role in API development with NodeJS and MongoDB?

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

You missed! Try again.

Next page of the Free Ebook:

8416. Creating a CRUD with NodeJS and MongoDB

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