vendredi 20 avril 2018

Mongo returns: Aggregate has empty pipeline

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!




Aucun commentaire:

Enregistrer un commentaire