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

前端 未结 2 576
谎友^
谎友^ 2020-12-07 03:13

I\'m trying to create some tests for my Mongoose models, and I can\'t figure out how to get the Jest/Mockgoose test to pass for a shorthand query/aggregation pipeline (see b

2条回答
  •  既然无缘
    2020-12-07 03:42

    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 method return 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))
    
        })
    }
    

提交回复
热议问题