0

I am trying to get 2 random documents within a collection called 'templates' but I only get an Internal Server Error.

I have successfully tested the following code in the mongo shell:

    db.templates.aggregate([{"$sample":{"size":2}}])

Could there be a problem with the fastify syntax?

    module.exports = async fastify => {
      fastify.get(
        '/',
        {
          schema: {
            response: {
              200: {
                type: 'object',
                items: {
                  type: 'object',
                  properties: {
                    _id: {
                      type: 'string'
                    }
                  }
                }
              }
            }
          }
        },
        async (req, res) => {
          try {
            const result = this.mongo.db
              .collection('templates')
              .aggregate([{ $sample: { size: 2 } }])
            return await result
          } catch (err) {
            res.internalServerError()
          }
        }
      )
    }

    module.exports.autoPrefix = '/questions'

I am getting an Internal Server Error, expecting 2 random documents.

Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55
Taaaz1964
  • 1
  • 4

1 Answers1

0

The problem is the handler of your route.

If you use arrow function the this is the upper scope, instead if you use a simple function this will bind to the fastify instance.

So you should change to:

async function (req, res) {
  try {
    const result = this.mongo.db // this will work as expected
      .collection('templates')
      .aggregate([{ $sample: { size: 2 } }])
      .toArray()
    return await result
  } catch (err) {
    res.internalServerError()
  }
}

Otherwise remove the this:

async (req, res) => {
  try {
    const result = fastify.mongo.db
      .collection('templates')
      .aggregate([{ $sample: { size: 2 } }])
    return await result
  } catch (err) {
    res.internalServerError()
  }
}
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73