当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Nodejs send function to ejs

问题描述:

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

});

}

in index.ejs :

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

// return no result but :

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

return a result in a terminal..

How should I proceed for display result in index.ejs? thanks

EDIT #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 // return undefined

but :

app.locals.count = function(id, call){

var myId = mongoose.Types.ObjectId(id)

var caca = 2;

call(caca);

}

in index.ejs // return 2

ccount function bad method return..

网友答案:

just register this function on app.locals rest of you rout logic remains same. now you can call the function on ejs

in 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 ;

in index.ejs

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

If you are having properties like title,text etc i assume you can do something like this

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

    <li><%= item.text%></li>
</ul>
  <% }); %>
分享给朋友:
您可能感兴趣的文章:
随机阅读: