【问题标题】:MongoDB aggregate() - error "TypeError: Cannot call method 'forEach' of undefined"MongoDB聚合() - 错误“TypeError:无法调用未定义的方法'forEach'”
【发布时间】:2015-01-21 14:12:10
【问题描述】:

我在“script.js”中有以下脚本

conn = new Mongo();
db = conn.getDB("learn");
db.contracts.aggregate([
  { $match: { regionCode: '77' } },
  { $unwind: '$products' },
  { 
    $project: {  
      _id: '$_id',
      regNum: '$regNum',  
      prodName: '$products.name',  
      prodPrice: '$products.price'
    }
  },
  { $match: { 'prodName' : 'Water' } }
], {cursor:{}}).result.forEach(printjson);

我通过以下方式从命令提示符运行它

mongo script.js >> out.txt

在文件“out.txt”中我有错误

TypeError: 无法在 script.js 调用未定义的方法 'forEach'

同样的问题,当我从 mongo shell mongo.exe 运行脚本时(使用 load())。

当我从 Robomongo 0.8.4 运行相同的聚合命令时,我得到了连续的结果(3 个 json 格式的文档)。有谁知道,为什么会发生这种情况?

MongoDB 2.6.5 版

【问题讨论】:

    标签: javascript mongodb foreach mongodb-query


    【解决方案1】:

    您需要在没有result 变量访问权限的情况下运行它。 mongodb 在shell 中访问时返回的cursor 没有名为result 的属性,因此会出现错误。

    db.contracts.aggregate([
      { $match: { regionCode: '77' } },
      { $unwind: '$products' },
      { 
        $project: {  
          _id: '$_id',
          regNum: '$regNum',  
          prodName: '$products.name',  
          prodPrice: '$products.price'
        }
      },
      { $match: { 'prodName' : 'Water' } }
    ], {cursor:{}}).forEach(printjson);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2014-09-18
      • 2015-04-03
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多