order.js (router)
Other functions such as create order, delete order, get orders from MongoDB database works perfectly but //GET MONTHLY INCOME Part is not working. Can anyone please fix this problem??
const Order = require("../models/Order");
const {
verifyToken,
verifyTokenAndAuthorization,
verifyTokenAndAdmin,
} = require("./verifyToken");
const router = require("express").Router();
//CREATE
router.post("/", verifyToken, async (req, res) => {
const newOrder = new Order(req.body);
try {
const savedOrder = await newOrder.save();
res.status(200).json(savedOrder);
} catch (err) {
res.status(500).json(err);
}
});
//UPDATE
router.put("/:id", verifyTokenAndAdmin, async (req, res) => {
try {
const updatedOrder = await Order.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedOrder);
} catch (err) {
res.status(500).json(err);
}
});
//DELETE
router.delete("/:id", verifyTokenAndAdmin, async (req, res) => {
try {
await Order.findByIdAndDelete(req.params.id);
res.status(200).json("Order has been deleted...");
} catch (err) {
res.status(500).json(err);
}
});
//GET USER ORDERS
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const orders = await Order.find({ userId: req.params.userId });
res.status(200).json(orders);
} catch (err) {
res.status(500).json(err);
}
});
// //GET ALL
router.get("/", verifyTokenAndAdmin, async (req, res) => {
try {
const orders = await Order.find();
res.status(200).json(orders);
} catch (err) {
res.status(500).json(err);
}
});
// GET MONTHLY INCOME <-----
router.get("/income", verifyTokenAndAdmin, async (req, res) => {
const date = new Date();
const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));
try {
const income = await Order.aggregate([
{ $match: { createdAt: { $gte: previousMonth } } },
{
$project: {
month: { $month: "$createdAt" },
sales: "$amount",
},
},
{
$group: {
_id: "$month",
total: { $sum: "$sales" },
},
},
]);
res.status(200).json(income);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
Order.js (module)
This is the Order.js module
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
userId: { type: String, required: true },
products: [
{
productId: {
type: String,
},
quantity: {
type: Number,
default: 1,
},
},
],
amount: { type: Number, required: true },
address: { type: Object, required: true },
status: { type: String, default: "pending" },
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
index.js
In this part, I declared all the necessary routes along with the order route but I don’t know why only get “/income” part is not responding.
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const stripeRoute = require("./routes/stripe");
const cors = require("cors");
dotenv.config();
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log("DB Connection Successfull!"))
.catch((err) => {
console.log(err);
});
app.use(cors());
app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/products", productRoute);
app.use("/api/carts", cartRoute);
app.use("/api/orders", orderRoute);
app.use("/api/checkout", stripeRoute);
const port = process.env.PORT;
app.listen(port || 5000 , () => {
console.log(`Backend server is running on port ${port}!`);
});
verifyToken.js
const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authenticated!");
}
};
const verifyTokenAndAuthorization = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.id === req.params.id || req.user.isAdmin) {
next();
} else {
res.status(403).json("You are not alowed to do that!");
}
});
};
const verifyTokenAndAdmin = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.isAdmin) {
next();
} else {
res.status(403).json("You are not alowed to do that!");
}
});
};
module.exports = {
verifyToken,
verifyTokenAndAuthorization,
verifyTokenAndAdmin,
};