OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

TypeError: Cannot read properties of undefined (reading 'collection') getting error at line 82 which has db.collection()

  • Thread starter Thread starter Jayesh Wani
  • Start date Start date
J

Jayesh Wani

Guest
I am working on a MongoDB project where i need to configure server for the database can anyone help with these. The files are added below for referrence, Please answer this question!!

index.mjs

Code:
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import students from "./routes/students.mjs";
import auth from "./routes/auth.mjs";

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

// Define routes
app.use("/api/students", students);
app.use("/api/auth", auth);

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack); // Log the error stack trace for debugging
    res.status(500).send("Uh oh! An unexpected error occurred.");
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

auth.mjs

Code:
import express from "express";
import bcrypt from "bcrypt";
import db from "../db/conn.mjs"; // Adjust path as needed
import { ObjectId } from "mongodb";

const saltRounds = 10;
const router = express.Router();

// Helper function to validate password
async function validatePassword(password, hash) {
    try {
        const match = await bcrypt.compare(password, hash);
        return match;
    } catch (err) {
        console.error(err.message);
        return false;
    }
}

// Sign-In Route
router.post('/signin', async (req, res) => {
    try {
        const { email, password } = req.body;

        // Ensure MongoDB connection is established
        await db();

        // Check if email exists in DB
        const user = await db.collection('users').findOne({ email });
        if (!user) {
            return res.status(400).send('User not found');
        }

        // Validate password
        const isValidPassword = await validatePassword(password, user.password);
        if (!isValidPassword) {
            return res.status(400).send('Invalid password');
        }

        res.status(200).send('Sign in successful');
    } catch (err) {
        console.error(err);
        res.status(500).send('An error occurred');
    }
});

// Sign-Out Route
router.post('/signout', (req, res) => {
    res.status(200).send('Sign out successful');
});

// Sign-Up Route
router.post('/signup', async (req, res) => {
    const {
        fullName, email, phone, branch,
        currYear, yearOfJoining, password,
        acmMemberId
    } = req.body;

    // Check if any required fields are missing
    const errors = {};
    if (!fullName) errors.fullName = "Full Name is required";
    if (!email) errors.email = "Email is required";
    if (!phone) errors.phone = "Phone number is required";
    if (!branch) errors.branch = "Branch is required";
    if (!currYear) errors.currYear = "Current year is required";
    if (!yearOfJoining) errors.yearOfJoining = "Year of joining is required";
    if (!password) errors.password = "Password is required";
    if (!acmMemberId) errors.acmMemberId = "ACM Member ID is required";

    // If there are errors, return them
    if (Object.keys(errors).length > 0) {
        return res.status(400).json(errors);
    }

    // If all required fields are present, continue with processing
    try {
        // Hash password
        const hashedPassword = await bcrypt.hash(password, saltRounds);

        // Insert new user into DB
        const result = await db.collection('users').insertOne({
            fullName, email, phone, branch,
            currYear, yearOfJoining, password: hashedPassword,
            acmMemberId, points: 0
        });

        res.status(201).send('User created successfully');
    } catch (err) {
        console.error(err);
        res.status(500).send('An error occurred');
    }
});


export default router;

conn.mjs

Code:
import { MongoClient } from "mongodb";
import dotenv from "dotenv";

dotenv.config();

const connectionString = `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASS}@acm-backend.jbgki1q.mongodb.net`;
const client = new MongoClient(connectionString);

let db;

(async () => {
    try {
        await client.connect();
        db = client.db("acm-backend");
        console.log("Connected to MongoDB");
    } catch (e) {
        console.error("Failed to connect to MongoDB", e);
    }
})();

export default db;

I tried POST api call using postman but was not able to get output or return the required json answer. I am expecting the data to be inserted in database.

Code:
{
  "fullName": "John Doe",
  "email": "[email protected]",
  "phone": "1234567890",
  "branch": "CSE",
  "currYear": "3",
  "yearOfJoining": "2020",
  "password": "securepassword",
  "acmMemberId": "12345",
  "points": "0"
}

<p>I am working on a MongoDB project where i need to configure server for the database can anyone help with these.
The files are added below for referrence, Please answer this question!!</p>
<p><strong>index.mjs</strong></p>
<pre><code>import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import students from "./routes/students.mjs";
import auth from "./routes/auth.mjs";

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

// Define routes
app.use("/api/students", students);
app.use("/api/auth", auth);

// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack trace for debugging
res.status(500).send("Uh oh! An unexpected error occurred.");
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

</code></pre>
<p><strong>auth.mjs</strong></p>
<pre><code>
import express from "express";
import bcrypt from "bcrypt";
import db from "../db/conn.mjs"; // Adjust path as needed
import { ObjectId } from "mongodb";

const saltRounds = 10;
const router = express.Router();

// Helper function to validate password
async function validatePassword(password, hash) {
try {
const match = await bcrypt.compare(password, hash);
return match;
} catch (err) {
console.error(err.message);
return false;
}
}

// Sign-In Route
router.post('/signin', async (req, res) => {
try {
const { email, password } = req.body;

// Ensure MongoDB connection is established
await db();

// Check if email exists in DB
const user = await db.collection('users').findOne({ email });
if (!user) {
return res.status(400).send('User not found');
}

// Validate password
const isValidPassword = await validatePassword(password, user.password);
if (!isValidPassword) {
return res.status(400).send('Invalid password');
}

res.status(200).send('Sign in successful');
} catch (err) {
console.error(err);
res.status(500).send('An error occurred');
}
});

// Sign-Out Route
router.post('/signout', (req, res) => {
res.status(200).send('Sign out successful');
});

// Sign-Up Route
router.post('/signup', async (req, res) => {
const {
fullName, email, phone, branch,
currYear, yearOfJoining, password,
acmMemberId
} = req.body;

// Check if any required fields are missing
const errors = {};
if (!fullName) errors.fullName = "Full Name is required";
if (!email) errors.email = "Email is required";
if (!phone) errors.phone = "Phone number is required";
if (!branch) errors.branch = "Branch is required";
if (!currYear) errors.currYear = "Current year is required";
if (!yearOfJoining) errors.yearOfJoining = "Year of joining is required";
if (!password) errors.password = "Password is required";
if (!acmMemberId) errors.acmMemberId = "ACM Member ID is required";

// If there are errors, return them
if (Object.keys(errors).length > 0) {
return res.status(400).json(errors);
}

// If all required fields are present, continue with processing
try {
// Hash password
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Insert new user into DB
const result = await db.collection('users').insertOne({
fullName, email, phone, branch,
currYear, yearOfJoining, password: hashedPassword,
acmMemberId, points: 0
});

res.status(201).send('User created successfully');
} catch (err) {
console.error(err);
res.status(500).send('An error occurred');
}
});


export default router;

</code></pre>
<p><strong>conn.mjs</strong></p>
<pre><code>import { MongoClient } from "mongodb";
import dotenv from "dotenv";

dotenv.config();

const connectionString = `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASS}@acm-backend.jbgki1q.mongodb.net`;
const client = new MongoClient(connectionString);

let db;

(async () => {
try {
await client.connect();
db = client.db("acm-backend");
console.log("Connected to MongoDB");
} catch (e) {
console.error("Failed to connect to MongoDB", e);
}
})();

export default db;

</code></pre>
<p>I tried POST api call using postman but was not able to get output or return the required json answer. I am expecting the data to be inserted in database.</p>
<pre><code>{
"fullName": "John Doe",
"email": "[email protected]",
"phone": "1234567890",
"branch": "CSE",
"currYear": "3",
"yearOfJoining": "2020",
"password": "securepassword",
"acmMemberId": "12345",
"points": "0"
}

</code></pre>
 

Latest posts

Online statistics

Members online
1
Guests online
5
Total visitors
6
Top