Open In App

How to Connect Node to a MongoDB Database ?

Last Updated : 14 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. Instead of rows & columns, MongoDB used collections & documents to store data. A collections consist of a set of documents & a document consists of key-value pairs which are the basic unit of data in MongoDB.

Make sure that MongoDB installs on your PC.

To connect a Node.js application to MongoDB, we have to use a library called Mongoose.  

const mongoose = require("mongoose");

After that, we have to call the connect method of Mongoose

mongoose.connect("mongodb://localhost:27017/collectionName", {
useNewUrlParser: true,
useUnifiedTopology: true
});

Then we have to define a schema. A schema is a structure, that gives information about how the data is being stored in a collection.

Example: Suppose we want to store information from a contact form of a website.

const contactSchema = {
email: String,
query: String,
};

Then we have to create a model using that schema which is then used to store data in a document as objects.

const Contact = mongoose.model("Contact", contactSchema);

Then, finally, we are able to store data in our document.

app.post("/contact", function (req, res) {
const contact = new Contact({
email: req.body.email,
query: req.body.query,
});
contact.save(function (err) {
if (err) {
res.redirect("/error");
} else {
res.redirect("/thank-you");
}
});
});

Example: Below is the code example of how to connect node.js to a mongodb database.

Javascript




const express = require("express");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
 
mongoose.connect(
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
 
const contactSchema = {
    email: String,
    query: String,
};
 
const Contact =
    mongoose.model("Contact", contactSchema);
 
const app = express();
 
app.set("view engine", "ejs");
 
app.use(bodyParser.urlencoded({
    extended: true
}));
 
app.use(express.static(__dirname + '/public'));
 
app.get("/contact",
    function (req, res) {
        res.render("contact");
    });
 
app.post("/contact",
    function (req, res) {
        console.log(req.body.email);
        const contact = new Contact({
            email: req.body.email,
            query: req.body.query,
        });
        contact.save(function (err) {
            if (err) {
                throw err;
            } else {
                res.render("contact");
            }
        });
    });
 
app.listen(3000,
    function () {
        console.log("App is running on Port 3000");
    });


HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <form action="/contact" method="post">
        <input type="text"
               placeholder="Email"
               name="email">
        <input type="text"
               placeholder="Query"
               name="query">
        <button type="submit">
            Submit
        </button>
    </form>
</body>
 
</html>


Output:

Output



Similar Reads

How to connect MongoDB database in a Node.js Applications ?
Node.js is a built-in JavaScript Chrome platform to easily build faster and more flexible network applications. Node.js uses an event-driven, uninterrupted I / O model that makes it easy and efficient, suitable for real-time applications that use data that works on all distributed devices. Node.js is an open-source, cross-platform working environme
2 min read
How to Connect to a MongoDB Database Using the Node.js Driver ?
MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your backend application built by Node.js. Setup for Dat
4 min read
How to Connect to a MongoDB Database Using Node.js
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJS app using the following command: npm init -ycd f
4 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
Nodejs - Connect MongoDB with Node app using MongooseJS
Connect the MongoDB database using MongooseJS to our NodeJS application Before we dive into looking how the mongoDB connects with a nodejs app using mongooseJS, lets get a brief intro to these technologies which are ruling the web development domain of today. Node: Node.js (Node) is an open source development platform for executing JavaScript code
3 min read
How to connect mongodb Server with Node.js ?
mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction) Parameters: This method accept two parameters as mentioned above and described below: Path/URL: The Path
2 min read
How to Connect Node.js To MongoDB Atlas Using Mongoose?
MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutorial, we will go through the process of how to connec
6 min read
How to connect sqlite3 database using Node.js ?
In this article, we are going to see how to connect the sqlite3 database using nodejs. So for this, we are going to use the Database function which is available in sqlite3. SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process
2 min read
How to connect the components using Connect() in React Redux
In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using connect( ), your components can access the store'
3 min read
How to find all the values of particular key of MongoDB Database using Node.js ?
MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() is the main method that is used for connecting to the MongoDB database which is running on a particular server on your machine (Refer to this article). We can also use pr
2 min read