1

Hello i am following a guide from freecodecamp on youtube about how to create backend app on replit using mongodb and node.js but when i run the code i get this error:

Cannot read properties of undefined (reading 'connect')

here is the link to my replit: https://replit.com/@tamerkarar/Moviereviews

on the guide the code run without error

i tried to use the uri without SECRET and it is still not working

  • 1
    It looks like you have a typo somewhere in your code. You have `MongoClinet.connect()` and I suspect you meant `MongoClient.connect()`. Please post your code so we can help you debug. – jQueeny Aug 14 '23 at 19:43
  • Oh you was right it was typo after i replaced every clinet with client the code is working now – Tamer Karar Aug 14 '23 at 19:47

1 Answers1

0

Here is the basic example of MongoClient with node.js

const express = require("express");
const app = express();
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);

const PORT = 5000;
// Database Name
const dbName = "reactdb";

app.use(express.urlencoded({
  extended:true
}));

app.use(express.json());

client
  .connect()
  .then(() => {
    console.log("database connected successfully");
  })
  .catch(() => client.close());

app.get("/getusers", async (req, res) => {
  var database = client.db(dbName);
  let result = await database.collection("tblusers").find().toArray();
  return res.status(200).json({
    msg: "record fetched successfully",
    data: result,
  });
});

app.post("/registeruser", async (req, res) => {
  let userdetails = {
    UserName: req.body.UserName,
    Password: req.body.Password,
    Age: parseInt(req.body.Age),
    Mobile: req.body.Mobile,
    Subscribed: req.body.Subscribed === "true" ? true : false,
  };

  var database = client.db(dbName);
  let result = await database.collection("tblusers").insertOne(userdetails);

  if (result.acknowledged) {
    return res.status(200).json({
      msg: "record inserted successfully",
    });
  }

  res.status(400).json({ msg: "internal server error" });
});

app.listen(PORT, () => {
  console.log("server listening on : " + PORT);
});
Jerry
  • 1,005
  • 2
  • 13