Monthly Data Statistics using Aggregate in MongoDB

PHOTO EMBED

Sun Mar 20 2022 19:10:44 GMT+0000 (UTC)

Saved by @youngDumb #mongo #nodejs

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const orderSchema = new Schema(
  {
    userId: {
      type: ObjectId,
      ref: "User",
    },
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    size: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      required: true,
    },
    quantity: {
      type: Number,
      default: 1,
    },
    totalPrice: {
      type: Number,
      required: true,
    },
    paymentMethod: {
      type: String,
      default: "Stripe",
    },
  },
  { timestamps: true }
);

module.exports = Order = mongoose.model("Order", orderSchema);


// @routes  GET api/order/income
// @desc    Get monthly income
// @access  Private - Admin
router.get("/income", isAuthenticatedAndAdmin, (req, res) => {
  const date = new Date();
  const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
  const previousMonth = new Date(date.setMonth(lastMonth.getMonth() - 1));

  Order.aggregate([
    { $match: { createdAt: { $gte: previousMonth } } },
    { $project: { month: { $month: "$createdAt" }, sales: "$amount" } },
    { $group: { _id: "$month", total: { $sum: "$sales" } } },
  ])
    .then((income) => res.status(200).json(income))
    .catch((err) => res.status(500).json(err));
});
content_copyCOPY