exports.getComments=function(query,skip,limit,callback){
Comment.find(query).sort({create_time:-1}).skip(skip).limit(limit).exec(function(error,comments){
if(error){
callback(error,null);
}
comments.foreach(function(index,comment){
Comment.find({reply_ID:comment.comment_ID}, function(err, replys){
comment.reply=replys;
});
});
callback(error,comments);
})
我的想法是将comment增加一个reply属性,然后再返回comments集合,但由于Comment.find是异步的,故向各位大虾求助,提供点解决方案的,初学,求照顾
回复 (9)
Y
谢谢你的回答,但这样的话貌似会触发N次callback
Y
我的解决思路:
Comment.find(query).sort({create_time:-1}).skip(skip).limit(limit).exec(function(error,comments){
if (comments.length === 0) {
return callback(error, []);
}
var proxy = new EventProxy();
var done = function () {
return callback(error, comments);
};
proxy.after('reply', comments.length, done);
comments.forEach(function(comment,index){
Comment.find({reply_ID:comment.comment_ID},function(error,replys){
comment.reply=replys;
proxy.trigger('reply',replys);
})
})
});
感觉应该可以吧
F
那你能不能说一下你这段代码到底是什意思?比如comment 是什么。 我们才能给你答案。没头没尾的贴出代码谁能看懂。
V
not tested, might work:
var ln = comments.length
comments.foreach(function(index, comment) {
Comment.find({ reply_ID: comment.comment_ID}, function(err, replys) {
comment.reply = replys;
ln --
if (ln === 0) {
callback(null, comments);
}
});
});'
Y
@saighost 嗯,好来,正在看
Y
引用 venngomeznot tested, might work: var ln = comments.length comments.foreach(function(index, comment) { Com...
这种方式我试过了,貌似不行,我用EventProxy解决了,参考了一下咱们论坛的源码
Y
引用 firstgeniusboy那你能不能说一下你这段代码到底是什意思?比如comment 是什么。 我们才能给你答案。没头没尾的贴出代码谁能看懂。
我这个就是一个评论,回复模块,就像咱们现在这个club一样,你评论就是comment,我再回复你就是reply,关联id就是reply_id=comment_id,评论和回复都放在了同一个表里面
W
为何不写在存储过程里
Y
引用 wldlzt为何不写在存储过程里
MongoDB的存储过程还真不清楚
参与回复
登录后即可参与回复。登录