Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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);
  //customer routes
  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);
  //customer routes
  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)
Posted
Updated 23-Jan-23 22:36pm
Comments
Richard MacCutchan 24-Jan-23 6:13am    
The problem is at line 29 of orderController.js. And the issue is simple, the variable reference req.user has not been initiaised, so it does not point to a valid user type. You will need to do some debugging to find out why that is so.

1 solution

The dot before the _id is probably causing the problem -
const orders = await Order.findOne({ customerId: req.user._id });


You are receiving the req.user detail which then should be concatenated to the id i.e. you have returneda user with name tan, he has an id of 25 -
req.user + _id
this then should read tan25 and not tan._25.

The error is pointing you the the problem, trust above will solve it.
 
Share this answer
 
Comments
tan25 24-Jan-23 5:41am    
this solution didn't work for me
const orders = await Order.find({ customerId: req.user + _id });

^

ReferenceError: _id is not defined
Richard MacCutchan 24-Jan-23 6:08am    
The issue is that req.user is null.
tan25 24-Jan-23 8:05am    
how can i correct this.
Richard MacCutchan 24-Jan-23 8:18am    
See my comment to your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900