Mongodb错误:除了聚合解释之外,'cursor'选项是必需的

时间:2017-05-13 17:22:31

标签: node.js mongodb mongoose

我使用mongodb 3.5.5和mongoose 4.9.8而Node.js版本是7.10,当我将我的应用程序发布到生产服务器时,错误发生了,但在我的开发环境中工作。

我该如何修复它们?

错误消息:

{ MongoError: The 'cursor' option is required, except for aggregation explain
     at Function.MongoError.create (/data/deploy/aaa/webapp/node_modules/mongodb-core/lib/error.js:31:11)
     at /data/deploy/aaa/webapp/node_modules/mongodb-core/lib/connection/pool.js:489:72
     at authenticateStragglers (/data/deploy/aaa/webapp/node_modules/mongodb-core/lib/connection/pool.js:435:16)
     at Connection.messageHandler (/data/deploy/aaa/webapp/node_modules/mongodb-core/lib/connection/pool.js:469:5)
     at Socket.<anonymous> (/data/deploy/aaa/webapp/node_modules/mongodb-core/lib/connection/connection.js:321:22)
     at emitOne (events.js:96:13)
     at Socket.emit (events.js:191:7)
     at readableAddChunk (_stream_readable.js:178:18)
     at Socket.Readable.push (_stream_readable.js:136:10)
     at TCP.onread (net.js:561:20)
   name: 'MongoError',
   message: 'The \'cursor\' option is required, except for aggregation explain',
   ok: 0,
   errmsg: 'The \'cursor\' option is required, except for aggregation explain',
   code: 9,
   codeName: 'FailedToParse' }

js code:

  articleLikeSchema.statics.sumById = function ({id = ''} = {}) {
    return this.model('ArticleLike').aggregate([
      { $match: { id: id } },
      { $group: { _id: '$id', count: { $sum: 1 } } }
    ]).then(sum => {
      if (!sum || sum.length === 0) return Promise.resolve({count: 0})
      else return Promise.resolve(sum[0])
    })
  }

Mongoose执行命令:

Mongoose: articlelikes.aggregate([ { '$match': { id: '1494606935' } }, { '$group': { _id: '$id', count: { '$sum': 1 } } } ], {})

2 个答案:

答案 0 :(得分:4)

您需要为在Mongo 3.6中更改的汇总呼叫提供光标选项

https://docs.mongodb.com/manual/reference/command/aggregate/#dbcmd.aggregate

因此,将{cursor:{}}添加到您的汇总调用中应该可以解决此问题:

  articleLikeSchema.statics.sumById = function ({id = ''} = {}) {
    return this.model('ArticleLike').aggregate([
          { $match: { 
                id: id 
              } 
          },
          { $group: { 
                _id: '$id', 
                count: { $sum: 1 } 
              } 
          }
        ], 
        { cursor:{} }
    ).then(sum => {
      if (!sum || sum.length === 0) return Promise.resolve({count: 0})
      else return Promise.resolve(sum[0])
    })
  }

答案 1 :(得分:0)

使用Mongoose 3.6,Mongoose 4.13.20,Node 6.11.0 +“回调方法”,我必须这样做:

return this.model('ArticleLike').aggregate([
      { $match: { id: id } },
      { $group: { _id: '$id', count: { $sum: 1 } } }
    ]).exec(function (err, results) {
      // ...
    })

无需添加包含{ cursor: {} }的参数。