在 app.js 中:
app.locals.count = function(id, call) {
var myId = mongoose.Types.ObjectId(id)
db.collection('comment').aggregate({$match: {postid: myId}}, {$group : {_id: '$postid', nb: {$sum: 1}}},
function(err, cb){
for (i = 0; i < cb.length; i++) { var la = cb[i]; return call(la.nb); };
});
}
在 index.ejs 中:
<% count(indexpost._id, function( result ){ %> <%= result %> <% }); %>
// 不返回结果但是:
<% count(indexpost._id, function( result ){ %> <%= console.log(result) %> <% }); %>
在终端中返回结果..
我应该如何继续在 index.ejs 中显示结果?谢谢
编辑#1 ####################################
app.locals.count = function(id, call){
var myId = mongoose.Types.ObjectId(id)
var caca = ccount(myId);
call(caca);
}
function ccount(myId){
db.collection('comment').aggregate({$match: {postid: myId}}, {$group : {_id: '$postid', nb: {$sum: 1}}},
function(err, cb){
for (i = 0; i < cb.length; i++) {
var la = cb[i];
var value = la.nb;
return la.nb;
};
});
}
在 index.ejs // 返回未定义
但 :
app.locals.count = function(id, call){
var myId = mongoose.Types.ObjectId(id)
var caca = 2;
call(caca);
}
在 index.ejs // 返回 2
ccount 函数错误的方法返回..