我有一个 Mongoose 查询 我想用计数查询的结果更新 Entry 对象的“entry_count”属性 但我无法更新导出的数据。
我可以获取数据但无法导出
这是我的查询代码:
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;
}
我可以使用 util 在控制台屏幕上按 log,但无法导出更新的数据。 为什么不能这样做? 请帮助我,提前致谢。
最佳答案
你兑现 promise 的太早了。在 _.each
内的所有 exec
调用完成之前,您不应调用 deferred.fulfill
。
所以类似:
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});
}
});
});
});
});
关于javascript - Mongoose 查询结果无法与数据对象一起导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25150273/