1

I am trying to get a random image from my db. I try to do that using a aggregate query:

exports.findRandomImage = (req, res) => {
    Image.aggregate({ $sample: { size: 1 } }, function (error, image) {
        if (error) {
            console.error(error)
        }
        res.send({
            title: image.title,
            description: image.description,
            url: image.url
        })
    })
}

This outputs two errors:

  • Error: Aggregate has empty pipeline
  • TypeError: Cannot read property 'title' of undefined

When I do the query from the mongo command line:

db.images.aggregate({ $sample: {size: 1} })

It properly returns an Image object. So I don't understand why image is undefined (logging image also returns undefined). Am I using the aggregate function wrong?

Thanks in advance!

joedoesnotknow
  • 73
  • 1
  • 2
  • 8
  • 1
    `Image.aggregate([{ $sample: { size: 1 } }], ...` Using `.aggregate()` without wrapping the pipeline in `[]` is deprecated. It was always bad practice, but only previously supported for legacy reasons. – Neil Lunn Apr 21 '18 at 00:14
  • Also see [Mongoose find() not returning result](https://stackoverflow.com/questions/23100328/mongoose-find-not-returning-result) and make sure you are pointing at the correct collection in the first place. – Neil Lunn Apr 21 '18 at 02:07

0 Answers0