Mongoose aggregation query fails in Jest/Mockgoose test, works elsewhere Mongoose aggregation query fails in Jest/Mockgoose test, works elsewhere mongoose mongoose

Mongoose aggregation query fails in Jest/Mockgoose test, works elsewhere


I have faced similar kind of problem and after researching a lot I found that that it was due to older version of mongoose as earlier versions are not compatible with breaking changes in MongoDB 3.6 and above.

I upgraded mongoose version one by one and I found that it works perfectly fine with mongoose version 4.12.2 or above (mongoose@4.12.2).

You can upgrade your mongoose version by running following command:

npm install mongoose@4.12.2


Finally figured this out: I had to add a cursor call to the aggregation pipeline, and translate it into a stream. To maintain the Promise I had the query methodreturn a Promise that resolves with data once the stream has ended, as below:

activitySchema.query.getUnused = function() {    return new Promise((res, rej) => {        let data = []        return Activity.aggregate()            .lookup({                from: 'userActivity',                localField: '_id',                foreignField: 'activity',                as: 'matched_docs',            })            .match({ matched_docs: { $eq: [] } })            .sample(1)            .project({ matched_docs: 0, __v: 0 })            .cursor({})            .exec()            .on('data', doc => data.push(doc))            .on('end', () => res(data))    })}