Recently delving into the realm of javascript, I am currently tackling a dashboard project that requires displaying the total quantity of each product ordered. Although I have successfully defined a variable 'qty' to represent the quantity of an individual product, I am facing challenges in calculating the overall quantity of said product from all orders. Provided below is my current progress along with any pertinent documents for reference. Any assistance or advice offered on navigating this task would be greatly appreciated.
Extract from orderRouter.js
const qty = await Order.aggregate([
{
$group: {
_id: '$name',
count: { $sum:'$qty'},
},
},
]);
orderRouter.js
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import Order from '../models/orderModel.js';
import User from '../models/userModel.js';
import Product from '../models/productModel.js';
import {isAdmin, isAuth, isSellerOrAdmin} from '../utils.js';
const orderRouter = express.Router();
orderRouter.get(
'/',
isAuth,
isSellerOrAdmin,
expressAsyncHandler(async (req, res) => {
const seller = req.query.seller || '';
const sellerFilter = seller ? { seller } : {};
const orders = await Order.find({ ...sellerFilter }).populate(
'user',
'name',
);
res.send(orders);
})
);
orderRouter.get(
'/summary',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const orders = await Order.aggregate([
{
$group: {
_id: '$name',
count: { $sum:'$qty'},
},
},
]);
res.send({ qty });
})
);
orderRouter.get(
'/mine',
isAuth,
expressAsyncHandler(async (req, res) => {
const orders = await Order.find({ user: req.user._id });
res.send(orders);
})
);
orderRouter.post(
'/',
isAuth,
expressAsyncHandler(async (req, res) => {
if (req.body.orderItems.length === 0) {
res.status(400).send({ message: 'Cart is empty' });
} else {
const order = new Order({
seller: req.body.orderItems[0].seller,
orderItems: req.body.orderItems,
shippingAddress: req.body.shippingAddress,
paymentMethod: req.body.paymentMethod,
itemsPrice: req.body.itemsPrice,
shippingPrice: req.body.shippingPrice,
taxPrice: req.body.taxPrice,
totalPrice: req.body.totalPrice,
user: req.user._id,
});
const createdOrder = await order.save();
res
.status(201)
.send({ message: 'New Order Created', order: createdOrder });
}
})
);
orderRouter.get(
'/:id',
isAuth,
expressAsyncHandler(async (req, res) => {
const order = await Order.findById(req.params.id);
if (order) {
res.send(order);
} else {
res.status(404).send({ message: 'Order Not Found' });
}
})
);
export default orderRouter;
orderModel.js
const orderSchema = new mongoose.Schema(
{
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
},
},
],
);
const Order = mongoose.model('Order', orderSchema);
export default Order;