1

I have been trying to retrieve some data but i keep getting an error. Here's a snippet from my routes, please let me know what's wrong with it. I'm trying to get jobID from collection 2 which is represented by category in collection 1. Hope it makes sense.

I get this error UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: The 'cursor' option is required, except for aggregate with the explain argument

router.get('/jobs/:type', (req, res, next)=>{
   Job.aggregate([
       { $match : { category: req.params.type, "bidcounter": { $gt:-1, $lt:5} } },
       {
           $lookup:
             {
               from: "job_cat",
               localField: "category",
               foreignField: "jobID",
               as: "product_cat"
             }
        }, { $sort : { date : -1} }
   ], function(err, jobs){
       res.json(jobs);
   });
});
Dng
  • 633
  • 1
  • 8
  • 14

2 Answers2

1

A couple solutions to help you debug:

First, set a promise library to give you the ability to .catch your errors.

Adding promise library to mongoose

Now you can do this:

Job.aggregate([{
            $match: {
                category: req.params.type,
                "bidcounter": {
                    $gt: -1,
                    $lt: 5
                }
            }
        },
        {
            $lookup: {
                from: "job_cat",
                localField: "category",
                foreignField: "jobID",
                as: "product_cat"
            }
        }, {
            $sort: {
                date: -1
            }
        }
    ])
    .catch((err) => {
        //error, its handled now!
    })

To see what the error is you can do this, but I remember reading somewhere that this isn't considered best practice.

I have used it in the past just see where my error is coming from.

process.on('unhandledRejection', error => {

  console.log('unhandledRejection', error.message);
}); 
cop
  • 603
  • 1
  • 6
  • 13
1

MongoDB changed in 3.6 how the aggregation command works. Aggregations require now a cursor. from ref https://github.com/Mockgoose/Mockgoose/issues/32 let pipeline contain business logic then below may help

 Job.aggregate(pipeline)
  .cursor({})
    .exec((err, results)=>{
    console.log(err, results)
    })
shivshankar
  • 2,067
  • 1
  • 18
  • 28