MERN Stack Tutorial Guide Doesn't Work

Hello, I’m following How To Use MERN Stack: A Complete Guide | MongoDB step-by-step and I don’t get the message “Successfully connected to MongoDB.”
When I copy the “server/node_modules” folder from the referenced git repository (GitHub - mongodb-developer/mern-stack-example: Mern Stack code for the Mern Tutorial), it does work and I do get the message.
Does the step-by-step guide omit the installation of a package? Which would that be and how would I install it by hand?

1 Like

Hello :wave: @53ac1da52812ebe8d38b9c0f38be5d9,

Welcome to the MongoDB Community forums :sparkles:

Could you please let us know the error message you are receiving?

I cannot find the server/node_modules folder in the given git repository. Could you please share the link to the folder that you copied?

Regards,
Kushagra

Hi, I get no error message. I only see “Server is running on port: 5000” when in the guide it says that I should see

Server is running on port: 5000
Successfully connected to MongoDB.

Regarding your second question, apologies, I have to be more precise: when I set up a project with the code from the repo, I move to its “server” folder and type “npm install mongodb express cors dotenv” That creates a server/nodes_modules folder. When I then copy that server/nodes_module folder into my project that I built following the step-by-step guide, it works and shows “Server is running on port: 5000 Successfully connected to MongoDB.”

To summarize:

  • I build a project following the step-by-step guide → “node server.js” shows only “Server is running on port: 5000”

  • I build a project using the code from the repository, install the packages in its “server” folder with “npm install mongodb express cors dotenv”, copy the server/node_modules folder from there into the project that was built following the step-by-step guide and replace its server/node_modules folder → “node server.js” shows “Server is running on port: 5000 Successfully connected to MongoDB.”

Why is the server/node_modules folder different when I build it in the project with the repo and what is the difference?

Hello @53ac1da52812ebe8d38b9c0f38be5d9,

Thanks for sharing the detailed explanation.

The cause for this issue is that the repository uses an older version of the MongoDB node.js driver, specifically, version "mongodb": "^3.6.6". On the other hand, when you create your own project and install the MongoDB node.js driver package, it installs the latest version, which is "mongodb": "^5.3.0".

However, the latest version is incompatible with the code written in the tutorial because it uses the callback function which is deprecated in the new MongoDB node.js driver 5.0.0.

Reference: Changelog - node-mongodb-native.

If you want to follow the tutorial and build the project successfully, you have to use MongoDB version mongodb@4.16.0 or a lower version.

To resolve this problem and make your project functional, you must delete the node_module directory and modify the MongoDB version in your package.json file to "mongodb": "^4.16.0" or a lower version.


Another workaround is to use the latest node.js driver version and modify the functions that use a callback by switching to the Promise and async/await syntax instead.

As an example, you can update the content of the db/conn.js file to incorporate async/await. Sharing code snippet for your reference:

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

let _db;

module.exports = {
    connectToServer: async function () {
        try {
            const db = await client.connect();
            // Verify we got a good "db" object
            if (db) {
                _db = db.db("employees");
                console.log("Successfully connected to MongoDB.");
            }
            return _db;
        } catch (err) {
            throw err;
        }
    },

    getDb: function () {
        return _db;
    },
};

Similarly, you can modify the function in routes/record.js.

I hope this helps. If you have any further questions, please let us know.

Best,
Kushagra

2 Likes

Hi @Kushagra_Kesav ,

I pasted your code for db/conn.js into the project I created according to the guide on the website and it worked! I see the message “Successfully connected to MongDB.” now. Thank you for your help.

You mention to also change the code in routes/records.js. I have tried to understand how to do that, but since I’m new to this topic, I wasn’t sure how. What changes would I make? Or do you have a resource that explains (to beginners) how they would go about it?

Yo Kushi,
I just tried something:

  • built the project according to the guide on the website
  • pasted your code into db/conn.js
  • copied the “client” folder from the git hub repository into it
  • website loads now, I can create records, but they are not displayed
  • MongoDB shows the created records

This is neither here, nor there… just experimenting and thought I’d write it up here. No clue how to change routes/record.js.

Hello :wave: @53ac1da52812ebe8d38b9c0f38be5d9,

The routes/record.js file contains five functions that handle CRUD operations. All of these functions are written as callback functions, as follows:

recordRoutes.route("/record").get(function (req, res) {
  let db_connect = dbo.getDb("employees");
  db_connect
    .collection("records")
    .find({})
    .toArray(function (err, result) {
      if (err) throw err;
      res.json(result);
    });
});

To use the latest version of the MongoDB Node.js driver, it’s recommended to convert these callback functions to use async/await syntax. Here’s an example of how to convert the above function:

recordRoutes.route("/record").get(async function (req, res) {
  try {
    const db_connect = await dbo.getDb("employees");
    const result = await db_connect.collection("records").find({}).toArray();
    res.json(result);
  } catch (err) {
    throw err;
  }
});

You’ll need to convert all five functions in the same pattern to be compatible with the latest Node.js driver module.

Please refer to the documentation to learn the fundamentals of Promises and Callback.

I hope this is helpful! Let us know if you have any questions.

Regards,
Kushagra

2 Likes

I don’t get the message → “Successfully connected to MongoDB.”

this message has nothing to do with routing, and controllers.

Look this example:

Who marked this as the solution? Shouldn’t I be the judge of that?

At any rate: it’s the solution! I changed routes/record.js. Check this out:

const express = require("express");
 
// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();
 
// This will help us connect to the database
const dbo = require("../db/conn");
 
// This help convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;
 
 
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(async function (req, res) {
  try {
    const db_connect = await dbo.getDb("employees");
    const result = await db_connect.collection("records").find({}).toArray();
    res.json(result);
  } catch (err) {
    throw err;
  }
});
 
// This section will help you get a single record by id
recordRoutes.route("/record/:id").get(async function (req, res) {
  try {
    const db_connect = await dbo.getDb();
    const myquery = { _id: ObjectId(req.params.id) };
    const result = await db_connect.collection("records").findOne(myquery);
    res.json(result);
  } catch (err) {
    throw err;
  }
});
 
// This section will help you create a new record.
recordRoutes.route("/record/add").post(async function (req, res) {
  try {
    const db_connect = await dbo.getDb();
    const myobj = {
      name: req.body.name,
      position: req.body.position,
      level: req.body.level,
    };
    const result = await db_connect.collection("records").insertOne(myobj);
    res.json(result);
  } catch (err) {
    throw err;
  }
});
 
// This section will help you update a record by id.
recordRoutes.route("/update/:id").post(async function (req, res) {
  try {
    const db_connect = await dbo.getDb();
    const myquery = { _id: ObjectId(req.params.id) };
    const newvalues = {
      $set: {
        name: req.body.name,
        position: req.body.position,
        level: req.body.level,
      },
    };
    const result = await db_connect.collection("records").updateOne(myquery, newvalues);
    console.log("1 document updated");
    res.json(result);
  } catch (err) {
    throw err;
  }
});
 
// This section will help you delete a record
recordRoutes.route("/:id").delete(async function (req, res) {
  try {
    const db_connect = await dbo.getDb();
    const myquery = { _id: new ObjectId(req.params.id) };
    const result = await db_connect.collection("records").deleteOne(myquery);
    console.log("1 document deleted");
    res.json(result);
  } catch (err) {
    throw err;
  }
});

 
module.exports = recordRoutes;

Started the server, started the frontend, and it works.
The “Create Record” link moved which makes me slightly uneasy, but I’ll deal with it later on. The functionality seems to be there.

Thank you for your help!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.