Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb error : The 'cursor' option is required, except for aggregation explain

I am using the mongodb 3.5.5 with mongoose 4.9.8 and the Node.js version is 7.10, when I publish my app to production server, the error was happened, but in my develop environment is work.

How can I fix them?

The error message:

{ 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])
    })
  }

The Mongoose execute command:

Mongoose: articlelikes.aggregate([ { '$match': { id: '1494606935' } }, { '$group': { _id: '$id', count: { '$sum': 1 } } } ], {})
like image 253
Tericky Shih Avatar asked May 13 '17 17:05

Tericky Shih


1 Answers

You need to provide cursor option for aggregate calls which is changed in Mongo 3.6

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

So adding {cursor:{}} to you aggregate call should resolve this problem:

  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])
    })
  }
like image 59
Himanshu Avatar answered Sep 22 '22 06:09

Himanshu