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

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"fullName": "John Doe",
"email": "[email protected]",
"phone": "1234567890",
"branch": "CSE",
"currYear": "3",
"yearOfJoining": "2020",
"password": "securepassword",
"acmMemberId": "12345",
"points": "0"
}
</code>
<code>{ "fullName": "John Doe", "email": "[email protected]", "phone": "1234567890", "branch": "CSE", "currYear": "3", "yearOfJoining": "2020", "password": "securepassword", "acmMemberId": "12345", "points": "0" } </code>
{
  "fullName": "John Doe",
  "email": "[email protected]",
  "phone": "1234567890",
  "branch": "CSE",
  "currYear": "3",
  "yearOfJoining": "2020",
  "password": "securepassword",
  "acmMemberId": "12345",
  "points": "0"
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật