【问题标题】:Nodejs send function to ejsNodejs 向 ejs 发送函数
【发布时间】:2015-02-19 03:42:54
【问题描述】:

在 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;
};
});
}

in index.ejs // 返回未定义

但是:

app.locals.count = function(id, call){
var myId =  mongoose.Types.ObjectId(id)
var caca = 2;
call(caca);
}

在 index.ejs 中 // 返回 2

ccount 函数错误方法返回..

【问题讨论】:

    标签: node.js function express ejs embedded-javascript


    【解决方案1】:

    只需在 app.locals 上注册此功能,其余的 rout 逻辑保持不变。现在你可以在 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>
      <% }); %>
    

    【讨论】:

    • 结果在控制台中显示什么?你试过forEach部分吗?
    • 不,结果是一个数字:
    • 所以在控制台中是 1,2,3,4,5 这样的?
    • GET / 304 36.328 毫秒 - - 2 1 7 8 0
    • 获取索引后导致终端/
    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2018-07-31
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多