【问题标题】:async.apply for mongodb aggregate function failsasync.apply for mongodb 聚合函数失败
【发布时间】:2017-06-23 20:26:53
【问题描述】:

我尝试借助异步库将我的回调地狱代码转换为更结构化的代码。现在,我有以下代码:

db.collection('campaigns').aggregate(pipeline, function(err, campaigns) {
   capCampaigns(campaigns, function(err, cappedCampaigns) {
     // etc  
   }
});

我改写成

async.waterfall([
  async.apply(db.collection('campaigns').aggregate, pipeline),
  capCampaigns,
 // etc
], function(err, result) {

}

很遗憾,async.apply 失败了:

TypeError: Cannot read property 's' of null
    at Collection.aggregate (/home/beryllium/sitesrv/node_modules/mongodb/lib/collection.js:2458:35)
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:760:23
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:166:37
    at fn (/home/beryllium/sitesrv/node_modules/async/lib/async.js:746:34)
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:1213:16
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:166:37
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:706:43
    at /home/beryllium/sitesrv/node_modules/async/lib/async.js:167:37
    at Object.async.waterfall (/home/beryllium/sitesrv/node_modules/async/lib/async.js:710:44)
    at chooseCampaignAndBanner (/home/beryllium/sitesrv/routes/banner.js:207:9)

我做错了什么?

其他信息: 节点版本:5.7.1 用于 NOdeJS 的 MonogDB 驱动程序:2.1.2

mongo 失败的那一行:

// Build the command
  var command = { aggregate : this.s.name, pipeline : pipeline};

【问题讨论】:

  • 如何准确地向您展示“回调地狱”代码!然后,只是问 “我尝试的方式不起作用 :(” 然后有人可以看一下并可能建议另一个更好的选择。想象一下!另外请描述您的代码所指的实际问题解决问题,因为通常另一双眼睛可能会再次看到更好的方法。“修复我的语法”问题永远不会得到最佳答案。
  • 在 capCampaign 之后有一些 6 个函数瀑布。所以,我希望在同一段落中命名函数而不是 6 倍缩进。这正是 async.waterfall,不是吗?
  • 是我在评论后半部分要去的地方。如果您真的在阅读结果,然后有 6 个以下异步调用,那对我来说是“重新思考”。在我编写的任何代码中,我唯一有类似 6 个调用的地方是这些调用实际上是并行的,而不是像瀑布所暗示的那样串联。
  • 好吧,首先我聚合广告系列(主要通过 $match 过滤),从中我找到标记的广告系列,我应该调用远程服务器并更新它们的价格。然后我根据 cookie 值过滤我拥有的广告系列 - 这只是循环我拥有的一系列广告系列。这个过滤功能不需要IO,但我还是把它放在瀑布中统一。然后,如果在该过滤器之后没有广告系列,我会再次致电 DB 以获取默认广告系列。实际上,它的串联功能少于 6 个。在您看来使用瀑布是不正确的吗?

标签: node.js mongodb aggregation-framework async.js


【解决方案1】:

您的代码将立即将管道应用到聚合方法,而且它无法在您的代码中回调。试试这个:

async.waterfall(
  [
    function(cb) { return db.collection('campaigns').aggregate(pipeline, cb) },
    capCampaigns,
  ], 
  function(err, result) {
  }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多