DEV Community

Romulo Gatto
Romulo Gatto

Posted on

MongoDB and Mongoose: Introduction to NoSQL Databases

MongoDB and Mongoose: Introduction to NoSQL Databases

What is a NoSQL Database?

Traditional relational databases have been the go-to choice for storing structured data in applications, but in recent years, there's been a rise in popularity of another type of database called NoSQL. As the name suggests, NoSQL (which stands for "Not Only SQL") is an alternative to traditional SQL-based databases.

Unlike relational databases that store data in tables with fixed schemas, NoSQL databases provide more flexible ways to structure and organize data. They are often used for applications that require scalability and high-performance handling of large amounts of unstructured or semi-structured data.

One popular NoSQL database is MongoDB. MongoDB is known for its fast performance and ability to handle big data workloads efficiently. In this guide, we'll explore how to get started with MongoDB using the Mongoose package.

Introducing MongoDB

MongoDB is a document-oriented NoSQL database system that stores data as JSON-like documents. The documents are stored within collections which are then organized into databases. Unlike tables in relational databases, collections do not require predefined schemas – each document can have different structures.

This flexibility allows developers to adapt their application's data model on the fly without having to worry about modifying complex table structures or migrating existing data.

Getting Started with Mongoose

Mongoose is an Object Data Modeling (ODM) library for Node.js applications that provides a straightforward approach to interacting with MongoDB. It adds schema validation, simplified querying syntax, middleware hooks, and other helpful functionalities on top of the native MongoDB driver.

To use Mongoose in your Node.js project:

  1. Install Mongoose by running npm install mongoose command.
  2. Require it at the top of your code files using const mongoose = require('mongoose');.
  3. Establish a connection between your application and the local or remote MongoDB server using mongoose.connect() method.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB!');
   })
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Make sure you replace 'mongodb://localhost/mydatabase' with the appropriate connection string for your database.

Creating Models and Schema

In Mongoose, models are a way of defining schemas for MongoDB documents. Schemas allow us to define the structure, data types, validation rules, and default values for our collections. They act as a blueprint that guides how our application interacts with the database.

Create a new file called user.js (or any other name you prefer) and add the following code:

const mongoose = require('mongoose');

// Define User schema
const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: { type: String, required:true },
});

// Create a User model based on the schema
module.exports = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

Here we have defined a simple User schema with three fields - name, age, and email. The required property ensures that an email address is mandatory when creating a new user document.

CRUD Operations with Mongoose

Mongoose simplifies CRUD operations by providing an easy-to-use API for creating, reading, updating, and deleting documents in MongoDB. Let's cover some basic examples:

Create Operation

To create a new document using Mongoose:

const User = require('./user');

// Instantiate a new User object
const newUser = new User({
  name: 'John',
  age: 25,
  email: 'john@example.com'
});

// Save it to the database
newUser.save()
  .then(() => {
    console.log('User created successfully!');
  })
  .catch((error) => {
    console.error('Error creating user:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Read Operation

To retrieve documents from the database:

// Find all users
User.find()
  .then((users) => {
    console.log(users);
  })
  .catch((error) => {
    console.error('Error retrieving users:', error);
  });

// Find a specific user by their email address
User.findOne({ email: 'john@example.com' })
   .then((user) => {
     console.log(user);
   })
   .catch((error) => {
     console.error('Error retrieving user:', error);
});
Enter fullscreen mode Exit fullscreen mode

Update Operation

To update an existing document:

// Find the user you want to update
User.findOne({ name: 'John' })
   .then((user)=>{
        // Change the desired field(s)
        user.age = 30;

        // Save the changes to the database
        return user.save();
   })
   .then(()=>{
      console.log("User updated successfully!");
})
.catch(console.error); 
Enter fullscreen mode Exit fullscreen mode

Delete Operation

To remove a document from MongoDB:

// Find and remove a specific user by their email address
User.findOneAndDelete({ email: 'john@example.com' })
.then(() =>{
console.log("Deleted User successfully!");
})
.catch(console.error);

// Remove all users in one operation (use with caution!)
/* User.deleteMany({})
.then(() =>{
console.log("All Users deleted successfully!");
})
.catch(console.error); */
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this guide, we introduced NoSQL databases and specifically focused on MongoDB as an example. We also explored how Mongoose simplifies working with MongoDB in Node.js applications.

By leveraging Mongoose's powerful features and functionalities, you can build robust and scalable applications that store, retrieve, update, and delete data seamlessly. Mongoose provides an intuitive API that abstracts away the complexities of MongoDB, allowing you to focus on your application's logic.

If you haven't already experimented with NoSQL databases or Mongoose, now is a great time to get started!

Top comments (0)