node and mongo DB

Connect MongoDB Atlas with NodeJS using Mongoose

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");
       }
   });
});

Prerequisites

  • Your local machine with Node.js & npm installed https://nodejs.org/
  • Create a new directory and initialize an empty Node.js project with npm init
  • A running instance of MongoDB with TLS configured
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

fifteen − 15 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top