Home > Net >  how can i get the sum of all orders for a specific seller?
how can i get the sum of all orders for a specific seller?

Time:11-02

I'm trying to get the total income of a specific seller. I already computed the total gross/income, but the problem here is instead of showing it only to the specific seller, it's also being shown to others. (please ignore the spent)

enter image description here

router.get("/total/:id", async (req, res) => {
const { id } = req.params;
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([
    {$group: {_id: "6360d4d5bd860240e258c582", total: {$sum: "$amount"} }}
  ])
  res.status(200).json(income);
} catch (err) {
  res.status(500).json(err);
}
});

OrderSchema

const OrderSchema = new mongoose.Schema({
    userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    products: [
        {
            productId:{
                type: mongoose.Schema.Types.ObjectId, ref: 'Product'
            },
            quantity: {
                type: Number,
                default: 1,
            },
            sellerId: {
                type: String
            }
        }
    ],
    amount: {type: Number,required: true},
    location:{type: Object, required:true},
    time: {type: String, required: true},
    status: {type:String, default: "pending"},
    tax: {type: Number,}

}, {timestamps: true}
)

export default mongoose.model('Order', OrderSchema)

But the problem is, other accounts can also see the total income

enter image description here

CodePudding user response:

You should first match the required documents, then group them, like this:

router.get("/total/:id", async (req, res) => {
const { id } = req.params;
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: {_id: id}},
    {$group: {_id: "$_id", total: {$sum: "$amount"} }}
  ])
  res.status(200).json(income);
} catch (err) {
  res.status(500).json(err);
}
});

CodePudding user response:

like what @Charchit said.

router.get("/total/:id", async (req, res) => {
    const { id } = req.params;
    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: {'products.sellerId': id},},
        {$group: {_id: "$products.sellerId", total: {$sum: "$amount"} }}
      ])
      console.log(id)
      res.status(200).json(income);
    } catch (err) {
      res.status(500).json(err);
    }
  });
  • Related