我正在MongoDB上执行聚合查询。结果将作为[object Object]返回。我无法弄清楚如何返回单个结果集。如果我执行result.forEach
循环,它会根据我的期望输出正确的个人计数。
架构:
var logbookSchema = new Schema({
id: String,
uid: String,
lid: { type: String, unique: true},
time : { type : Date, default: Date.now },
callsign: String,
contact: String,
start: String,
end: String,
frequency: String,
band: String,
mode: String,
RSTsent: String,
RSTrec: String,
notes: String
})
聚合功能:
Logbook = require("../models/logbook");
module.exports = function(user_id){
var today = new Date();
var todayMinus1Week = new Date();
todayMinus1Week = todayMinus1Week.setDate(todayMinus1Week.getDate() - 7);
console.log(today + " | " + todayMinus1Week)
Logbook.aggregate(
[
{ "$match": {
"time": {
"$gte": new Date(todayMinus1Week),"$lt": new Date(today)
},
"uid": user_id
}},
{ "$sort": {
time: -1
}},
{ "$group": {
"_id": {
"day": { "$dayOfMonth": "$time" },
"month": { "$month": "$time"}
},
"count": { "$sum": 1 }
}}
],
function(err,result) {
if(err){
console.log("Error:"+err);
}else{
console.log("Result ["+user_id+"]:"+result);
return result;
//result.forEach(function(entry){
//entries.push(entry);;
//});
}
}
);
};
路由器:
router.get('/dashboard', isAuthenticated, function(req, res, next) {
Logbook.find({ 'uid' : req.user.uid }, {}, { limit: 10}, function(err, logbook){
if (err) { console.log(err); return next(); }
var Entries = new LogbookData(req.user.uid);
res.render('dashboard', {
user: req.user,
logbook: logbook,
locals: {
firstName: req.session.firstName,
email: req.session.email,
admin: req.session.admin
},
title: 'QRZLog Dashboard v1.0',
recentEntries: Entries
});
});
});
答案 0 :(得分:0)
您的LogbookData
函数需要转换为异步函数,因为它依赖于异步函数本身。您不能从异步函数返回值;相反,你需要在函数完成时调用一个continuation函数。
要进行重组,您的代码应该与此类似:
// aggregate function; notice how it takes a callback function.
module.exports = function(user_id, callback) {
...
Logbook.aggregate(..., function(err,result) {
if (err) {
console.log("Error:", err);
return callback(err);
} else {
// FWIW, the following line fixes your `[object Object]` issue.
console.log("Result ["+user_id+"]: %j", result);
return callback(null, result);
}
}
};
// router
router.get('/dashboard', isAuthenticated, function(req, res, next) {
Logbook.find({ 'uid' : req.user.uid }, {}, { limit: 10}, function(err, logbook) {
// XXX: passing `err` with `next()` for proper error handling.
if (err) { console.log(err); return next(err); }
// XXX: no need to use `new` here.
LogbookData(req.user.uid, function(err, entries) {
if (err) { console.log(err); return next(err); }
res.render('dashboard', {
user: req.user,
logbook: logbook,
locals: {
firstName: req.session.firstName,
email: req.session.email,
admin: req.session.admin
},
title: 'QRZLog Dashboard v1.0',
recentEntries: entries
});
});
});
});