Integrating Mongodb with our Node backend server application

A server is basically an application that gets data from your database and sends it to your frontend application

All the complex/time consuming tasks should be performed on your backend server and not on the frontend application

Let's connect the database that we just created to the node application

Before that lets setup some starter code for our node application

This tutorial here assumes you have some prior knowledge of node. If you have not worked with node its totally fine, there are some very straight forward steps.

Go to the startserver function in your node application, once the application has started, copy the following lines of code

const mongodb = 'mongodb://localhost:27017/myprof...
copy
View More

Lets create the Model classes which define our entities

Project Structure

Node Project Structure

There are two schemas in this project, one is contacts which refers to the potential contact messages that we receive from our contact form in the react app, and another is subscribers which stores all the users who have subscribed to the tech blog or news letters

In this tutorial we'll create the first schema together, as an exercise I'll let you create the second one

Inside the db/schema/ folder lets create a folder for contacts Model. Here we'll initialize the model with the fields in that collection

import mongoose from 'mongoose';

const Schema = ...
copy
View More

If you havent yet created your controller yet, go ahead and create it with a get request - route /api/data/contacts

If you are having trouble setting up the node application, expand the following files below and copy them into your project

Great, now that you have your controller setup, lets access the Model that we exported from the Contacts model. Lets execute a find() query and send the response in the get request

const data = await ContactsModel.find().exec();
re...
copy
View More

Save the code and run your application

npm start
copy

Your app should've started on a port, check the console to see the port number. Open the browser and enter the following url and see that you the data that you inserted into the mongodb table

localhost:8000/api/data/contacts
copy

Lets create another API to create a contact entry that we can later integrate with our react application

async function createContacts (req, res) {
	const...
copy
View More

Download and install Postman if you don't already have it

Create a new Post request and hit the localhost:8000/api/data/contacts url

Postman request

That is all you need to do to create a backend server and integrate it with your data store which in this case is mongodb

That brings us to the end of integrating mongodb with node application tutorial

Next TutorialBack to: Mongodb TutorialNext TutorialNext Tutorial: React Native
Scroll to top