• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read

Express.js is widely recognized as a Node.js web framework for creating online applications/API and MongoDB is a popular NoSQL document-oriented database. Together with MongoDB and Express.js you can build scalable and flexible web applications.

Advertisements

In this article, I will explain how to use MongoDB with Express to retrieve data via a web server. To start with first, let’s install Express.js and Mongoose first. Mongoose is a Node.js framework to interact with MongoDB.

Refer to Using MongoDB from the Node.js to learn how to connect and work with MongoDB from Node.js

1. Install Express and MongoDB Mongoose

As a prerequisite, first, install Node.js and MongoDB. After that, we required the install express for Express.js framework and Mongoose to interact with MongoDB. The following command uses npm to install the dependencies express and mongoose


# Install express
$ npm install express

# Install mongoose
$ npm install mongoose

2. Create a Web Server with the Express.js framework

As the installation process has been done in the above section. Now, we create the Node.js server application that uses the Express.js framework to create a web server that listens on port 3000. The source code is provided below.


# create  Node.js server application
const express = require("express");

const app = express();
app.use(express.json());
app.listen(3000, () => {
  console.log("The server is active on port 3000");
});

Here, we first import the Express.js library and assign it to the variable express. After that, the port variable is provided with a port value of 3000. Then, a route for the root URL path (“/”) is defined. When a client sends an HTTP GET request to the server’s root URL, the server responds by sending the string MongoDB Express Tutorial as the response.

Add the above content to MyFile.js and run the node MyFile.js command, then launch a web browser and go to http://localhost:3000. We can see the server responds to the string below.

mongodb express usage

3. Establish MongoDB Connection

The next attempt is the MongoDB connection via mongoose and use this connect to retrive data to Express framework. Here, we offer a Node.js application’s fundamental template for utilizing Mongoose to connect to a MongoDB database.


# MongoDB connection via mongoose
const mongoose = require("mongoose");

const server = '127.0.0.1:27017'; 
const database = 'MyDB'; 
class Database {
  constructor() {
    this._connect();
  }
  _connect() {
    mongoose
      .connect(`mongodb://${server}/${database}`)
      .then(() => {
        console.log('Database connection successful');
      })
      .catch((err) => {
        console.error('Database connection failed');
      });
  }
}

module.exports = new Database();

First, we define a Database class that establishes a connection to a MongoDB database using Mongoose. It specifies the server address and database name as 127.0.0.1:27017 and MyDB, respectively. The execution MyFile.js represents the connection message with the MongoDB database.

Installing express

4. Create the Database Schema

Once the MongoDB connection is built, we can define the schema database of Mongoose. We need to add the following template in the file MyFile.js.


# define the schema database of mongoose
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number,
});

The code here defines the Mongoose schema for a user object with three properties: name, email, and age. The schema is defined using mongoose.Schema() method, which takes an object that specifies the properties of the schema. Each property in the schema object corresponds to a property in the user object and specifies the property’s data type.

5. Define and save a new Document

As the schema has been established in this section, we use this schema to build Mongoose models, which represent collections in the MongoDB database.


# Using schema to build Mongoose models
const User = mongoose.model('User', userSchema);
const newUser = new User({
  name: 'Elena John',
  email: '[email protected]',
  age: 22,
});

newUser.save()
.then(() => {
  console.log('Save User at MongoDB');
})
.catch((error) => {
  console.error(error);
});

In the above code, we define a new user object using a Mongoose model and save it to a MongoDB database using the save() method. Thus, the save operation is successful because the code logs a message to the console indicating that the user was saved.

Installing express

6. Building Posts and Get endpoints

Finally, we can perform the POST and GET endpoints using the Express framework for a Node.js server to retrieve the data from MongoDB. We have defined the given code in the same file MyFile.js.


# performing POST and GET endpoints using Express framework
app.post("User", async (request, response) => {
  const user = new User(request.body);
  try {
    await user.save();
    response.send(user);
  } catch (error) {
    response.status(500).send(error);
  }
});
app.get("/users", async (request, response) => {
  const users = await User.find({});
  try {
    response.send(users);
  } catch (error) {
    response.status(500).send(error);
  }
});

The user data is fetched by browsing the link: http://localhost:3000/users

Installing express

7. Conclusion

In conclusion, we have performed the basic operation of MongodB with the Express. Despite that, we can build powerful and flexible web applications by using MongoDB with Express.js that can handle large amounts of data and scale to meet the users’ needs.