【发布时间】: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