top of page

Connecting the Node Server to a MongoDB


Connecting the Node Server to a MongoDB
Connecting the Node Server to a MongoDB

MongoDB is a Nodejs NoSQL database. We will use the MongoDB driver for nodejs to administer the MongoDB database. MongoDB stores data in binary JSON format. We'll also utilize the Mongoose tool to connect MongoDB to Node JS and control the database (creating, reading, updating, and deleting documents). MongoDB, like traditional databases, is simple to use and saves time.


Mongoose.js integrates MongoDB clusters or collections with your Node.js application. It allows you to design schemas for your documents. When generating and dealing with schemas, Mongoose has a lot to offer.


In this tutorial, we will look at how to connect a MongoDB instance to a Node.js application.


How to Use Mongoose to Connect MongoDB to Node.js


MongoDB is one of the most popular No-SQL databases in the developer community today. Instead of SQL objects, No-SQL databases allow developers to transmit and retrieve data as JSON documents. Mongoose can be used to interact with MongoDB in a Node.js application.


Basic Requirements


● Basic knowledge of relational databases, such as SQL.

● Excellent understanding of JavaScript, objects, and data types.

● Your machine must have Nodejs and the MongoDB database installed.

● Nodejs and MongoDB paths must be added to the PATH environment variable.


What is Exactly Mongoose?


Mongoose is a MongoDB and Node.js object modeling tool. In practice, this implies that you can specify your data model in just one place: your code. It allows us to define schemas for our data while abstracting access to MongoDB. In this manner, we can ensure that all saved documents have the same structure and include the necessary characteristics.


Basic Terminologies


There is a slew of terminology in the Mongoose model that you should know. They are as follows:


Schema


A data structure description. A Schema describes the names of the fields and their corresponding times, which aids with validation, defaults, and other options in our models.


Model


A model is the most essential tool for dealing with MongoDB. It's a clever document constructor. Models are in charge of creating and reading documents from the MongoDB database.


Validation


MongoDB does not need all documents in a collection to have the same schema by default. In other words, the fields and data types in the documents do not have to be the same. Validation helps you to establish the structure of a collection's documents.


What is a Node Server?


A Node server is a server-side runtime environment that allows JavaScript code to be run on the server. It is based on the Node.js runtime based on the V8 JavaScript engine in Google Chrome.


Node.js introduces the concept of server-side JavaScript, which allows developers to construct server applications in JavaScript, a language usually associated with client-side scripting in web browsers. This opens up new avenues for developing server-side applications that are efficient, scalable, and high-performing.


A Node server may handle a variety of functions, including request processing, business logic execution, database interaction, and dynamic content generation. It is a foundation for developing web servers, APIs, microservices, and real-time applications.


Node.js is well-known for its event-driven, non-blocking architecture, allowing it to handle many concurrent connections without interfering with other tasks. This makes it ideal for applications that require a high level of scalability and responsiveness.


The core Node.js modules, which provide fundamental functionality for processing network requests, file system operations, and other server-related tasks, can be used to develop Node servers. Third-party frameworks and libraries such as Express.js, Koa.js, or Nest.js can simplify server setup, routing, middleware administration, and other typical server-side activities.


With a Node server, developers can create full-stack JavaScript applications that share code and modules between client-side and server-side components. This allows for faster development, better code maintainability, and more seamless communication between the client and server.


Thus, a Node server is a Node.js-based server-side runtime environment that allows developers to run JavaScript code on the server. It is the foundation for developing scalable and high-performance server applications that handle responsibilities, including request processing, business logic execution, and data interaction. Node.js's non-blocking and event-driven nature makes it ideal for applications that require great scalability and responsiveness.


Installing Mongoose in a Node.js environment is the First Step


Step 1: Run the following commands on a terminal to create and navigate to a new folder.


$ mkdir mongoose_tutorial

$ cd mongoose_tutorial




Step 2: Then, on a terminal, use the following command to install Express and Mongoose.


$ npm install express Mongoose --save


Step 3: If you're using Yarn, execute:


$ yarn add express Mongoose


Establishing the connection is the Second Step


Step 1: To begin our Express.js server, create a new file called server.js. Add the following code to server.js to load Mongoose and Express.

server.js


const express = require("express");
const mongoose = require("mongoose");
const Router = require("./routes")

const app = express();
app.use(express.json());


Step 2: Using the Mongoose.connect() function, connect to a local MongoDB instance.


server.js
mongoose.connect('mongodb://localhost:27017/usersdb',
 
{
    useNewUrlParser: true,
    useFindAndModify: false,
   
useUnifiedTopology: true
 
}
);


Step 3: We authorise the use. To avoid the Deprecation Warning, pass NewUrlParser: true, etc., to Mongoose.connect().


Follow the steps below to connect to MongoDB Atlas.


Step 4: Go to the Cluster tab in MongoDB Atlas and click CONNECT.


Step 5: Connect your application and select Node.js as the driver.


Step 6: Make a copy of the connection string.


Step 7: With the connection, create the variables listed below and replace their values with your actual credentials.


server.js

const username = "<mongodb username>";
const password = "<password>";
const cluster = "<cluster name>";
const dbname = "myFirstDatabase";
mongoose.connect(
`mongodb+srv://${username}:${password}@${cluster}.mongodb.net/${dbname}?retryWrites=true&w=majority`,
 
{
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
 
}
);


Step 8: Add the following code directly below your Mongoose.connect() to ensure your connection was successful.

server.js

// ...
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
 
console.log("Connected successfully");
});


Step 9: Then configure the app to listen on port 3000

server.js
// ...
app.use(Router);
app.listen(3000, () => {
 
console.log


Step 10: The Router will be created later in the next steps.


Designing the Schema is the Third Step.


Step 1: Let's create a collection schema for our application now.


Step 2: Add the following code to another file, models.js.

models.js

const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
 
name: {
    type: String,
    required: true,
 
},
 
age: {
    type: Number,
    default: 0,
 
},
});

const User = mongoose.model("User", UserSchema);
module.exports = User;


Step 3: Using Mongoose, we create a schema called UserSchema—the schema () function. The schema captures the request's name and age fields.


The schema is then exported using the last two lines.


Make the POST endpoint the Fourth Step.


Step 1: Make a new file called routes.js. This file defines the app's endpoints.


Step 2: Add the following code to load express and the schema we generated in Step 3.

routes.js

const express = require("express");
const userModel = require("./models");
const app = express();


Step 3: Add the following code to construct the POST endpoint.


routes.js


// ...
app.post("/add_user", async (request, response) => {
    const user = new userModel(request.body);
    try {
      await user.save();
      response.send(user);
    } catch (error) {
      response.status(500).send(error);
    }
});

To add a new user to the database, we create a route called /add_user. Using the line const user = new userModel(request.body);, we parse the content to be saved to the database.

The object is then saved to the database using a try/catch block using the.save() method.


Making the GET endpoint is the Fifth Point


Step 1: Insert the following code into the routes.js file.

routes.js


// ...
app.get("/users", async (request, response) => {
 
const users = await userModel.find({});

 
try {
    response.send(users);
 
} catch (error) {
    response.status(500).send(error);
 
}
});


To access all users saved using the /add_user route, we establish a route /users. The.find() method retrieves these users from the database. We then send the users to this endpoint using a try/catch block.


Step 2: Finally, add the code below to export these endpoints.


routes.js

// ...


module.exports = app;


Step 3: Your application is now complete. Run the command below to serve the app.

$ node server.js


Endpoint Testing is the Sixth Step in this Process


Step 1: Let's put the two endpoints we made earlier to the test.


Step 2: Start Postman and send a POST request to the


Step 3: The database now contains a new user. You can confirm this by looking through your collections.


Step 4: Make a GET request to the endpoint http://localhost:3000/users.


Step 5: The endpoint returns a list of all users who have been added to the database.


We looked at how to set up Mongoose in this tutorial. We've also looked at how to connect to a database and develop a schema for our collections. Mongoose can connect your Node.js app to both MongoDB and MongoDB Atlas.


Benefits of Using Mongoose in MongoDB


When working with MongoDB databases, developers can benefit from using Mongoose, an Object Data Modelling (ODM) library for MongoDB:


Simplified Schema Management: Mongoose makes defining and managing database schemas easier. It enables developers to specify their data structure using a versatile and user-friendly schema syntax. Schemas can incorporate data types, validation rules, default values, and other features that make ensuring data integrity and consistency easy.


Data Validation: Mongoose has robust validation tools that enable developers to impose data validation rules at the application level. This helps to avoid saving erroneous or inconsistent data to the database, assuring data quality and reliability. Validation can be implemented at the schema level, making applying identical rules across several documents simple.


Middleware Functionality: Mongoose has middleware functionality, allowing developers to build pre- and post-save hooks, pre- and post-query hooks, and other middleware operations. This will enable developers to implement custom logic and conduct procedures such as data manipulation, validation, and logging before or after particular events, resulting in a flexible and modular approach to data work.


Mongoose has middleware functionality, allowing developers to build pre- and post-save hooks, pre- and post-query hooks, and other middleware operations. This will enable developers to implement custom logic and conduct procedures such as data manipulation, validation, and logging before or after particular events, resulting in a flexible and modular approach to data work.


Mongoose works effectively with the Express.js framework, a popular choice for constructing Node.js web applications. This integration enables developers to link their Express.js apps to MongoDB databases utilising the powerful features of Mongoose. It makes designing routes, processing requests, and connecting with databases easier, supporting efficient development and code organization.


Query Creation and Population: Mongoose includes a robust query API that makes querying MongoDB databases easier. It provides a chainable query builder interface that allows developers to create sophisticated inquiries using simple methods. Mongoose also supports population, which enables developers to obtain referenced documents from other collections, removing the need for manual joins and streamlining data retrieval.


Thus, employing Mongoose gives developers a solid and adaptable toolkit for working with MongoDB databases. It simplifies schema maintenance, allows data validation, provides middleware support for custom logic, has a robust query API, and interacts easily with Express.js. When working with MongoDB, these advantages increase productivity, maintainability, and overall development experience.

Conclusion


Finally, connecting a Node.js server to a MongoDB database provides various benefits for developers when developing scalable and data-driven apps.


Developers can build a safe and efficient connection between their Node.js server and the MongoDB database by employing the standard MongoDB Node.js driver or an ORM library like Mongoose. This link facilitates accessible communication and data interchange, allowing MongoDB's document-oriented data model to reach its full potential.


One of the most significant advantages is using JavaScript's power and flexibility throughout the stack. Developers may work with a consistent and familiar programming language when using Node.js as the server-side runtime environment and MongoDB as the database, simplifying the development process and lowering the learning curve.


Furthermore, Node.js's non-blocking and event-driven nature makes it a good choice for managing asynchronous database operations. Developers can use callbacks, promises, or async/await syntax to handle database queries, assuring efficient server resource utilisation and optimal speed.


Connecting a Node.js server to a MongoDB database also allows for smooth integration with other Node.js frameworks like Express.js and Nest.js. This connection enables developers to create rich RESTful APIs or GraphQL endpoints, efficiently managing requests and responses and exploiting MongoDB's extensive query capabilities.


Furthermore, MongoDB's flexible structure enables agile development and scalability. Developers can adjust data structures on the fly, accommodating changing application requirements without complex migrations. This versatility is beneficial in fast-paced development contexts where conditions regularly change.


Connecting a Node.js server to a MongoDB database allows developers to build highly performant, scalable, data-driven apps. It leverages the power of JavaScript across the entire stack, allows easy integration with other Node.js frameworks, supports asynchronous processes, and allows for agile development. By combining these technologies, developers may create modern and efficient systems that can manage massive amounts of data and react to changing business needs.


Interesting F.AQs


What is the popularity of MongoDB?


Gartner, a well-known research group, recently named MongoDB a leader in their Magic Quadrant report on operational database management systems in terms of completeness of vision and capacity to execute.


What is the MongoDB download rate?


In addition to these third-party sources, MongoDB's popularity is reflected in the number of software downloads, which now stands at 40 million and is growing. MongoDB is popular among developers for its ease of use and among businesses for its ability to solve a wide range of use cases.


Stay tuned to CipherSchools for more interesting tech articles.

8 views

Recent Posts

See All
bottom of page