【问题标题】:How to get random mongodb documents using aggregate() and $sample?如何使用 aggregate() 和 $sample 获取随机 mongodb 文档?
【发布时间】:2019-06-08 08:25:50
【问题描述】:

我试图在一个名为“模板”的集合中获取 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 个随机文档。

【问题讨论】:

  • 能否请您从您的 catch 块中打印出错误?

标签: node.js mongodb fastify


【解决方案1】:

问题在于您的路线的处理程序。

如果你使用箭头函数 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()
  }
}

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多