0

在 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 函数错误的方法返回..

4

1 回答 1

0

只需在 app.locals 上注册此功能,其余的路由逻辑保持不变。现在您可以在 ejs 上调用该函数

在 app.js 中:

function count(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);  };
});
}

app.locals.count =count ;

在 index.ejs 中

% count(indexpost._id, function( result ){ %> <%= result %> <% }); %>

如果你有标题、文本等属性,我假设你可以做这样的事情

  <% result.forEach(function(item) { %>
<ul>
    <li><%= item.title%></li>

    <li><%= item.text%></li>
</ul>
  <% }); %>
于 2014-12-20T10:04:49.880 回答