這是我的代碼的NodeJS執行錯誤回調和MongoDB
Event.find({ start_date: { $lte: new Date() }, end_date: { $gte: new Date() }, isDeleted: false }).limit(10).sort({ created_at: 'desc' }).populate('moderator').exec(function (err, events) {
if (err) throw err;
var response = [];
events.forEach(function (ev) {
var moderatorName = ev.moderator.facebook.name;
User.find({ currentEvent: ev._id }).exec(function (err, users) {
callback(null, users);
});
if (ev.isFanPage)
moderatorName = ev.fanPageName;
response.push({ eventId: ev._id, title: ev.name, description: ev.description, thumb: ev.thumb, moderator: moderatorName, moderatorFbId: ev.moderator.facebook.id, countPicture: ev.numberOfUploadedImages, countVideo: users });
});
next(response);
});
我要插入事件的用戶列表中現場contvideo了我的迴應。
我用不好的回調?
UPDATE 16/03/2016
我的解決辦法是在功能上查找用戶的事件調用回調函數。
我的功能找到用戶的事件。
exports.getEventUsers = function (id, next, callback) {
console.log("id evento " + id);
User.find({ currentEvent: id }).exec(function (err, users) {
if (err)
res.send("ERROR");
callback(users);
});};
我的理線事件是
Event.find({ isDeleted: false }).limit(10).sort({ created_at: 'desc' }).populate('moderator').exec(function (err, events) {
if (err) throw err;
var response = [];
var namearray = [];
var total = events.length;
console.log("cant evento" + total);
events.forEach(function (ev) {
var moderatorName = ev.moderator.facebook.name;
var usuario = [];
if (ev.isFanPage)
moderatorName = ev.fanPageName;
console.log("evento id " + ev._id);
exports.getEventUsers(ev._id,next,function(retorno) {
total--;
console.log("evento id " + ev._id);
console.log("cantidad elementos evento " + response.length);
response.push({ eventId: ev._id, title: ev.name, description: ev.description, thumb: ev.thumb, moderator: moderatorName, moderatorFbId: ev.moderator.facebook.id, countPicture: ev.numberOfUploadedImages, participantes: retorno.length });
if(total == 0)
next(response);
});
});
console.log("termino el proceso");
});
如果發生錯誤,您可以使用'next(err)',並在中間件中的所有路由之後處理它。 –