CJCoding With Joseph
15free / daySign inCreate account

NodeJs

Updates To Index.js

Connecting To MongoDB

Now that you have a database.js file with a connectToDb function, we need to update index.js so it stops using the JSON file and starts talking to MongoDB instead. We will keep this as simple as possible and only change what is needed.

You need to

  • Import connectToDb from database.js

  • Remove the JSON file code

  • Update the POST /contact route to save to MongoDB

  • Update the GET /messages route to read from MongoDB


Import the database helper

At the top of index.js, you probably have something like this:

const express = require("express");
const fs = require("fs");

We no longer need fs, and we want to import the connectToDb function we made from the database.js file. Change the top of index.js to this to import the function:

const express = require("express");
const { connectToDb } = require("./database");
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 8 more lessons in NodeJs.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.