我正在尝试使用 express 在 node.js 中开发一个应用程序
我有 activity、target 和 bfdwork 三个不同的 shcmeas
我一直试图得到下面提到的东西,但不知何故无法弄清楚如何
我使用了聚合函数,但它不是填充活动,我无法使目标与其对齐
任何人都可以帮忙吗?
1) Activity Schema
var mongoose = require("mongoose");
var addactivitySchema = new mongoose.Schema({
nmeofactivity:
{type:String,
required:true,
unique:true
},
categoryofactivity:{
type:String,
required:true,
}
});
module.exports=mongoose.model("Addactivity", addactivitySchema);
2) BFD work
//schema to add activities
var mongoose = require("mongoose");
var Addactivity = require("./addactivity");
var Village = require("./village");
var User = require("./users");
var bfdworkSchema = new mongoose.Schema({
nameofbfd:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
activityname:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Addactivity'
},
villagename:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Village'
},
wadiname:{type: String, required:true},
dateofcamp:{type: Date, required:true},
beneficiaries:{type:Number, required:true},
followup:{type:Number},
treatment:{type:Number},
createdon:{ type: Date, default: Date.now }
});
module.exports=mongoose.model("BFDWork", bfdworkSchema);
3) Target Schema
//schema for targets
var mongoose = require("mongoose");
var Addactivity = require("./addactivity");
var targetSchema = new mongoose.Schema({
year:Number,
activity: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Addactivity'
},
jantarget:Number,
febtarget:Number,
martarget:Number,
aprtarget:Number,
maytarget:Number,
juntarget:Number,
jultarget:Number,
augtarget:Number,
septarget:Number,
octtarget:Number,
novtarget:Number,
dectarget:Number,
createdon:{ type: Date, default: Date.now },
});
module.exports=mongoose.model("Target", targetSchema);
Below is the aggregate code
app.get("/getdata", (req,res)=>{
res.render("totalwork");
});
app.post("/getdata", (req, res) => {
const startDate = new Date(req.body.fromdate);
const endDate = new Date(req.body.todate);
BFDWork.find({})
.populate('activityname')
BFDWork.aggregate([
{
$match: {
dateofcamp: {
$gte: startDate,
$lte: endDate
}
}
},
{
$group: {
_id: "$activityname",
totalBeneficiaries: { $sum: "$beneficiaries" },
count: { $sum: 1 }
}
},
{
$project: {
_id: 0,
activity: "$_id",
totalBeneficiaries: 1,
count: 1
}
}
])
.exec(function(err, results) {
if (err) {
// Handle error
} else {
Target.find({}, (err, foundtarget)=>{
if(err){
res.redirect("/");
console.log(err);
}else{
Addactivity.find({}, (err, foundacti)=>{
if(err){
console.log(err);
res.redirect("/");
}else{
res.render("showdata", {results:results, foundtarget:foundtarget, foundacti:foundacti});
}
})
}
});
}
});
});