Skip to content

Main #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: mongodb
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
7 changes: 6 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
MyToken = 12345
PORT = 8000
PORT = 8000

DBURL= mongodb://localhost:27017/userEnquiry

// userEnquiry is the name of the database
// mongodb://localhost:27017 is the connection string to the MongoDB server
77 changes: 77 additions & 0 deletions app/controllers/web/userEnquiryController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const userEnquiryModel = require("../../models/enquiry.model");

// insert enquiry
let enquiryInsert = (req, res) => {
let { sName, sEmail, sPhone, sMessage } = req.body;

let enquiry = new userEnquiryModel({
name: sName,
email: sEmail,
phone: sPhone,
message: sMessage,
});

enquiry
.save()
.then(() => {
res.status(201).send({
status: "success",
message: "Enquiry Inserted & Saved Successfully",
});
})
.catch((err) => {
res.status(500).send({
status: "error",
message: "Enquiry Not Inserted",
error: err,
});
});
};

// get enquiry list
let enquiryList = async (req, res) => {
let enquiryList = await userEnquiryModel.find();
res
.status(200)
.json({ status: "success", message: "Enquiry List", data: enquiryList });
};

// delete enquiry
let enquiryDelete = async (req, res) => {
let enquiryId = req.params.id;

let deleteEnquiry = await userEnquiryModel.deleteOne({ _id: enquiryId });

res.status(200).json({
status: "success",
message: "Enquiry Deleted Successfully",
id: enquiryId,
data: deleteEnquiry,
});
};

// update enquiry
let enquiryUpdate = async (req, res) => {
let enquiryId = req.params.id;
let { sName, sEmail, sPhone, sMessage } = req.body;
let updateObj = {
name: sName,
email: sEmail,
phone: sPhone,
message: sMessage,
};

let updateEnquiry = await userEnquiryModel.updateOne(
{ _id: enquiryId },
updateObj
);

res.send({
status: "success",
message: "Enquiry Updated Successfully",
id: enquiryId,
data: updateEnquiry,
});
};

module.exports = { enquiryInsert, enquiryList, enquiryDelete, enquiryUpdate };
26 changes: 26 additions & 0 deletions app/models/enquiry.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
let mongoose = require("mongoose");

let userEnquirySchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
phone: {
type: String,
required: true,
},
message: {
type: String,
required: true,
},
});

let userEnquiryModel = mongoose.model("userEnquiry", userEnquirySchema); // Create a model for the schema // userEnquiryModel is the name of the model, and userEnquirySchema (fields) is the schema it uses
// The model name is used to create the collection in the database, and it will be pluralized (e.g., "userEnquiries"). // userEnquiries is the name of the collection (table_name) in the database. // The model is used to interact with the collection in the database, such as creating, reading, updating, and deleting documents.

module.exports = userEnquiryModel;
16 changes: 16 additions & 0 deletions app/routes/web/enquiryRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
let express = require("express");
let enquiryRoutes = express.Router();

const {
enquiryInsert,
enquiryList,
enquiryDelete,
enquiryUpdate,
} = require("../../controllers/web/userEnquiryController");

enquiryRoutes.post("/enquiry-insert", enquiryInsert);
enquiryRoutes.get("/enquiry-list", enquiryList);
enquiryRoutes.delete("/enquiry-delete/:id", enquiryDelete);
enquiryRoutes.put("/enquiry-update/:id", enquiryUpdate);

module.exports = enquiryRoutes;
12 changes: 12 additions & 0 deletions dbConnection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { MongoClient } = require("mongodb");
let dbConnectionUrl = "mongodb://127.0.0.1:27017"; // MongoDB connection URL

const client = new MongoClient(dbConnectionUrl); // Create a new MongoClient instance

let dbConnection = async () => {
await client.connect(); // Connect to the MongoDB server
let db = client.db("mongoDBPractice_dataBase"); // Specify the database to use
return db; // Return the database connection
};

module.exports = { dbConnection }; // Export the dbConnection function for use in other files
51 changes: 51 additions & 0 deletions index copy 2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
let express = require("express");
const { checkToken } = require("./Middleware/checkTokenMiddleware");
const { checkPass } = require("./Middleware/checkPassMiddleware");

require("dotenv").config(); // Load environment variables from .env file

let app = express();

//console.log(process.env.MyToken); // Access the environment variable

app.use(express.json()); // Middleware to parse JSON bodies

//app.use(checkToken); // Use the middleware for all routes

app.get("/", checkPass, (req, res) => {
res.send({ status: 1, msg: "Home Page API" });
});

app.get("/news", checkToken, (req, res) => {
res.send({ status: 1, msg: "News Page API" });
});

app.get("/news/:id", (req, res) => {
let currentId = req.params.id; // Access the URL parameter
res.send("News Details API" + currentId); // This will output the ID from the URL
});

app.get("/products", (req, res) => {
console.log(req);
res.send({ status: 1, msg: "Products Page API" });
});

app.post("/login", (req, res) => {
console.log(req.body); // Access the request body. mainly used for POST requests. object is passed in the body.

res.status(200).json({
status: 1,
msg: "Login API",
bodyData: req.body,
queryData: req.query,
});

/* res.send({
status: 1,
msg: "Login API",
bodyData: req.body,
queryData: req.query,
}); */
});

app.listen(process.env.PORT || 5000);
122 changes: 122 additions & 0 deletions index copy 3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
let express = require("express");
const { dbConnection } = require("./dbConnection");
const { ObjectId } = require("mongodb");

require("dotenv").config(); // Load environment variables from .env file

let app = express();

app.use(express.json()); // Middleware to parse JSON bodies

app.get("/student-read", async (req, res) => {
let myDB = await dbConnection();
let studentCollection = myDB.collection("students");

let data = await studentCollection.find().toArray(); // Find all documents in the collection

let resObj = {
status: "success",
message: "Student List",
result: data,
};

res.send(resObj); // Send the response object back to the client

res.send("Hello from student-read API, route!");
});

app.post("/student-insert", async (req, res) => {
let myDB = await dbConnection(); // Await the database connection
let studentCollection = myDB.collection("students"); // Specify the collection to use

/* let obj = {
sName: req.body.sName,
sEmail: req.body.sEmail,
}; */

let { sName, sEmail } = req.body; // Destructure the request body to get sName and sEmail
let obj = { sName, sEmail }; // Create an object with the destructured values

// Check if a student with the same email already exists
let existingStudent = await studentCollection.findOne({ sEmail });

//console.log(existingStudent); // Log the existing student to the console

if (existingStudent) {
return res.status(400).send({
status: "fail",
message: "A student with this email already exists.",
});
}

//console.log(obj); // Log the object to the console

let insertRes = await studentCollection.insertOne(obj); // Insert the object into the collection
let resObj = {
status: "success",
message: "Student inserted successfully",
data: insertRes, // Include the result of the insert operation in the response
};

res.status(201).send(resObj); // Send the response object back to the client

//res.send("Student Insert API!");
});

app.delete("/student-delete/:id", async (req, res) => {
let { id } = req.params;

let myDB = await dbConnection();
let studentCollection = myDB.collection("students");
let delRes = await studentCollection.deleteOne({ _id: new ObjectId(id) }); // Delete the document with the specified ID

//console.log(delRes); // Log the result of the delete operation to the console

let resObj = {
status: 1,
message: "Student deleted successfully",
delete: delRes,
};

res.send(resObj);

//let paramsData = req.params; // Get the request parameters
//console.log(paramsData); // Log the parameters to the console
});

app.put("/student-update/:id", async (req, res) => {
let { id } = req.params;
let { sName, sEmail } = req.body; // Destructure the request body to get sName and sEmail
//let obj = { sName, sEmail }; // Create an object with the destructured values

let obj = {};
if (sName !== "" && sName !== undefined && sName !== null) {
obj["sName"] = sName; // Add sName to the object if it's not empty or undefined
}

if (sEmail !== "" && sEmail !== undefined && sEmail !== null) {
obj["sEmail"] = sEmail; // Add sName to the object if it's not empty or undefined
}

console.log(obj);

let myDB = await dbConnection();
let studentCollection = myDB.collection("students");
let updateRes = await studentCollection.updateOne(
{ _id: new ObjectId(id) },
{ $set: obj } // Update the document with the specified ID using the $set operator
);

let resObj = {
status: 1,
message: "Student Updated successfully",
updateData: updateRes,
};

res.send(resObj);

//let paramsData = req.params; // Get the request parameters
//console.log(paramsData); // Log the parameters to the console
});

app.listen(process.env.PORT || 5000);
Loading