我正在Node Express和Mongoose后端上工作,我想计算Pending,In-Progress和Complete请求占请求总数的百分比。
我已经从请求总数的db中获取计数,并将其除以100,但是我还需要获得Pending,In-Progress和Complete计数。
totalcount: (req, res) => {
UserRequest.countDocuments()
.then(result => {
if (!result) res.json({ success: false, result: "No result found"});
res.json({success: true, result: result / 100 });
})
.catch(err => res.json({success: false, result: err}))
}
它应该返回:
待审核:30%
进行中:40%
完成:30%作为输出
答案 0 :(得分:0)
使用异步等待。构造代码会更容易。
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect("mongodb://localhost/stack-overflow", { useNewUrlParser: true })
const UserReqSchema = new Schema({
type: "String"
})
const UserReqModel = mongoose.model("UserReq", UserReqSchema)
async function counterFun() {
try {
const totalCount = await UserReqModel.countDocuments({})
const pendingCount = await UserReqModel.countDocuments({ type: "pending" })
const inprogressCount = await UserReqModel.countDocuments({ type: "inprogress" })
const completeCount = await UserReqModel.countDocuments({ type: "complete" })
console.log("pendingCount", (pendingCount/totalCount)*100);
console.log("inprogressCount", (inprogressCount/totalCount)*100);
console.log("completeCount", (completeCount/totalCount)*100);
} catch(error) {
console.log(error)
}
}
counterFun()