【问题标题】:mongoosse : How could I get a sum up total price猫鼬:我怎么才能得到总价的总和
【发布时间】:2022-11-10 00:20:05
【问题描述】:

我有一个用户模式,每个用户都有他们购买的记录。 现在,我需要得到每个用户的总成本,我怎样才能得到它们?

用户架构:

    const mongoose = require("mongoose");

    const userInfoSchema = new mongoose.Schema({
     userName: {
          type: String,
          required: [true, "A user must have a name"],
        },
    historyList:[
{ type: mongoose.Types.ObjectId, ref: "History" }
    ]
    })

    const UserInfo = mongoose.model("UserInfo", userInfoSchema);
    
    module.exports = UserInfo;

历史模式

const mongoose = require("mongoose");
const historySchema = new mongoose.Schema({
  source: {
    type: Number,
  },
  price: {
    type: Number,
  },
  time: {
    type: Date,
    default: Date.now(),
  },
});

const History = mongoose.model("History", historySchema);
module.exports = History;

** 我想得到一个用户的总费用,我卡在这里了 ...**

exports.getMyCost = async (req, res, next) => {
try {
    const user = await UserInfo.findById(req.body._id);
    let total = 0 ;
   for(let i = 0 ;i<user.historyList.length;i++){
total + = user.historyList.price ; // here comes out with undefine...
}

    res.status(200).json({
      code: 200,
      total: 
    });
  } catch (error) {
    return next(
      res.status(400).json({
        code: 400,
        msg: error.message,
      })
    );
  }

}

任何人都可以帮忙吗?非常感谢您!

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您已将 historyList 定义为参考数组,您必须先填充然后迭代数组。 https://mongoosejs.com/docs/populate.html#population

    const user = await UserInfo.findById(req.body._id).populate("historyList");
    let total = 0 ;
    for(let i = 0 ;i<user.historyList.length;i++){
       total + = user.historyList[i].price ; // here comes out with undefine...
    }
    

    尽管如此,我不建议这样做。我建议使用聚合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-11
      • 2021-07-10
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多