I have a mongoose query and I want update "entry_count" property of Entry object with result of count query but I can't update exported data.
I can get data but can't export
this is my query code:
getTopicList: function(limit) {
var deferred = promise.pending();
// create mongoose model from schemas
var Topic = mongoose.model('Topic');
var Entry = mongoose.model('Entry');
var queryDate = main.getCurrentDateString();
// get entry count created in today
Entry
.count({createdAtStr : queryDate})
.exec(function(err, entryCount) {
// get last valid topics [ limit -> arg0 ]
Topic
.find({ status : 1 })
.limit(limit)
.sort('-updatedAt')
.exec(function(err, data) {
_.each(data, function(single) {
Entry.
count({topic : single._id})
.exec(function(err, entryCnt) {
util.log(entryCnt);
single.entry_count = entryCnt;
});
});
deferred.fulfill({"status":true,"data":data});
});
});
return deferred.promise;
}
i can press log on console screen with util , but can't export updated data. why can't do this? please help me, thanks in advance.
You're fulfilling your promise too soon. You shouldn't be calling deferred.fulfill until all the exec calls within the _.each have completed.
So something like:
Entry
.count({createdAtStr : queryDate})
.exec(function(err, entryCount) {
// get last valid topics [ limit -> arg0 ]
Topic
.find({ status : 1 })
.limit(limit)
.sort('-updatedAt')
.exec(function(err, data) {
var numleft = data.length; // Count of outstanding count queries
_.each(data, function(single) {
Entry.
count({topic : single._id})
.exec(function(err, entryCnt) {
util.log(entryCnt);
single.entry_count = entryCnt;
if (--numleft === 0) {
// None left, so fullfill the promise.
deferred.fulfill({"status":true,"data":data});
}
});
});
});
});