orderController.js
const Order = require("../../../models/order");
function orderController() {
return {
store(req, res) {
const { phone, address } = req.body;
if (!phone || !address) {
req.flash("error", "All fields are required");
return res.redirect("/cart");
}
const order = new Order({
customerId: req.user._id,
items: req.session.cart.items,
phone,
address,
});
order
.save()
.then((result) => {
req.flash("success", "Order placed successfully");
return res.redirect("/");
})
.catch((err) => {
req.flash("error", "something went wrong");
return res.redirect("/cart");
});
},
async index(req, res) {
const orders = await Order.findOne({ customerId: req.user._id });
console.log(orders);
},
};
}
module.exports = orderController;
web.js
const homeController = require("../app/http/controllers/homeController");
const authController = require("../app/http/controllers/authController");
const cartController = require("../app/http/controllers/customers/cartController");
const orderController = require("../app/http/controllers/customers/orderController");
const guest = require("../app/http/middlewares/guest");
function initRoutes(app) {
app.get("/", homeController().index);
app.get("/login", guest, authController().login);
app.post("/login", authController().postLogin);
app.get("/register", guest, authController().register);
app.post("/register", authController().postRegister);
app.post("/logout", authController().logout);
app.get("/cart", cartController().index);
app.post("/update-cart", cartController().update);
app.post("/orders", orderController().store);
app.get("/customer/orders", orderController().index);
}
module.exports = initRoutes;
orderController.js
const Order = require("../../../models/order");
function orderController() {
return {
store(req, res) {
const { phone, address } = req.body;
if (!phone || !address) {
req.flash("error", "All fields are required");
return res.redirect("/cart");
}
const order = new Order({
customerId: req.user._id,
items: req.session.cart.items,
phone,
address,
});
order
.save()
.then((result) => {
req.flash("success", "Order placed successfully");
return res.redirect("/");
})
.catch((err) => {
req.flash("error", "something went wrong");
return res.redirect("/cart");
});
},
async index(req, res) {
const orders = await Order.findOne({ customerId: req.user._id });
console.log(orders);
},
};
}
module.exports = orderController;
web.js
const homeController = require("../app/http/controllers/homeController");
const authController = require("../app/http/controllers/authController");
const cartController = require("../app/http/controllers/customers/cartController");
const orderController = require("../app/http/controllers/customers/orderController");
const guest = require("../app/http/middlewares/guest");
function initRoutes(app) {
app.get("/", homeController().index);
app.get("/login", guest, authController().login);
app.post("/login", authController().postLogin);
app.get("/register", guest, authController().register);
app.post("/register", authController().postRegister);
app.post("/logout", authController().logout);
app.get("/cart", cartController().index);
app.post("/update-cart", cartController().update);
app.post("/orders", orderController().store);
app.get("/customer/orders", orderController().index);
}
module.exports = initRoutes;
order.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const orderSchema = new Schema(
{
customerId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
items: { type: Object, required: true },
phone: { type: String, required: true },
address: { type: String, required: true },
paymentType: { type: String, default: "COD" },
status: { type: String, default: "order_placed" },
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", orderSchema);
server.js
require("dotenv").config();
const express = require("express");
const app = express();
const ejs = require("ejs");
const path = require("path");
const passport = require("passport");
const expressLayout = require("express-ejs-layouts");
const PORT = process.env.PORT || 3000;
const mongoose = require("mongoose");
const session = require("express-session");
const flash = require("express-flash");
const MongoDbStore = require("connect-mongo")(session);
const url = "mongodb://127.0.0.1/pizza";
mongoose.set("strictQuery", false);
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const connection = mongoose.connection;
connection
.once("open", () => {
console.log("Database connected...");
})
.on("error", function (err) {
console.log("connection failed");
});
let mongoStore = new MongoDbStore({
mongooseConnection: connection,
collection: "sessions",
});
app.use(
session({
secret: process.env.COOKIE_SECRET,
resave: false,
saveUninitialized: false,
store: mongoStore,
cookie: { maxAge: 1000 * 15 },
})
);
const passportInit = require("./app/config/passport");
passportInit(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use((req, res, next) => {
res.locals.session = req.session;
res.locals.user = req.user;
next();
});
app.use(expressLayout);
app.set("views", path.join(__dirname, "/resources/views"));
app.set("view engine", "ejs");
require("./routes/web")(app);
app.listen(2000, () => {
console.log("Listening on 8002");
});
user.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
role: { type: String, default: "customer" },
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);
What I have tried:
I am getting the following error in the terminal :
const orders = await Order.findOne({ customerId: req.user._id }); ^
TypeError: Cannot read properties of undefined (reading '_id') at index (C:\Users\bhide\Desktop\best\pizza\app\http\controllers\customers\orderController.js:29:65) at Layer.handle [as handle_request] (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\layer.js:95:5) at C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\index.js:280:10) at module.exports (C:\Users\bhide\Desktop\best\pizza\node_modules\express-ejs-layouts\lib\express-layouts.js:116:3) at Layer.handle [as handle_request] (C:\Users\bhide\Desktop\best\pizza\node_modules\express\lib\router\layer.js:95:5)