0

我试图在一个名为“模板”的集合中获取 2 个随机文档,但我只得到一个内部服务器错误。

我已经在 mongo shell 中成功测试了以下代码:

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

fastify语法会不会有问题?

    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'

我收到内部服务器错误,需要 2 个随机文档。

4

1 回答 1

0

问题是您的路线的处理程序。

如果你使用箭头函数,this则它是上层作用域,相反,如果你使用简单函数this将绑定到 fastify 实例。

所以你应该改为:

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()
  }
}

否则删除this

async (req, res) => {
  try {
    const result = fastify.mongo.db
      .collection('templates')
      .aggregate([{ $sample: { size: 2 } }])
    return await result
  } catch (err) {
    res.internalServerError()
  }
}
于 2020-01-03T08:44:50.893 回答