我正在嘗試獲取特定賣家的總收入。我已經計算了總收入/總收入,但這里的問題不是只顯示給特定的賣家,它也顯示給其他人。(請忽略已用)

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);
}
});
訂單模式
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)
但問題是,其他賬戶也能看到總收入

uj5u.com熱心網友回復:
您應該首先匹配所需的檔案,然后將它們分組,如下所示:
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);
}
});
uj5u.com熱心網友回復:
就像@Charchit 所說的那樣。
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);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/525476.html
