javascript - Mongoose 查询结果无法与数据对象一起导出

标签 javascript node.js mongodb mongoose promise

我有一个 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/

相关文章:

javascript - Angular Guard 通过 cookies 中的 token 进行路由

javascript - CSS 文件在 NODE js 中不起作用

mongodb启动错误

mongodb - 使用Spring数据在Mongo Db集合中的某个字段查询时如何查找重复项

javascript - AttachEvent 将事件插入队列的开头,而 addEventListener 将事件追加到队列

javascript - Iron-router,Router.go() 没有完全渲染模板

使用 slider 更改 Javascript 图像

javascript - 安装 Express.js 后更改 node.js 项目名称

javascript - 修改指定文件时如何运行vue-cli build命令?

python - 具有以列表中指定的前缀开头的属性的对象的 MongoEngine 查询列表