【问题标题】:getting empty array and nothing else得到空数组,没有别的
【发布时间】:2019-06-28 19:30:14
【问题描述】:

这里的获取请求只是返回一个空数组。我不知道为什么。我已经看到其他看起来完全相同的代码工作得很好。

我已尝试在 Google 上搜索该问题,但没有看到相关答案。我正在使用 Postman 来测试它。


const getPantry = async (req, res) => {
    const results = await pantry.find({});
    return send(res, 200, results)
}


module.exports = cors(
    router(
        get('/pantry', getPantry),
    )
)

我期待一个 json 对象,但它只是返回空数组。

【问题讨论】:

  • 也许是个愚蠢的问题,但pantry 集合中有数据吗?
  • 一点也不傻。我有,但我确定无论出于何种原因,micro 根本无法在我的机器上运行。我想我应该关闭它。

标签: javascript node.js mongodb api micro


【解决方案1】:

根据你的例子,我能得到的最短的快速和肮脏的完整工作代码是这样的:

const { send } = require('micro')
const { router, get } = require('microrouter')
const { MongoClient } = require('mongodb')

var pantry = null

MongoClient.connect('mongodb://localhost')
  .then(conn => {
    pantry = conn.db('test').collection('pantry')
  })

const getPantry = async (req, res) => {
  const results = await pantry.find({}).toArray();
  send(res, 200, results)
}

module.exports = router(get('/pantry', getPantry))

使用curl调用端点:

$ curl 'http://localhost:3000/pantry'
[{"_id":0},{"_id":1},{"_id":2}]

正确显示集合的内容。

我相信您的代码中缺少的是 toArray() 方法。 find() 本身 returns a cursor 并且它不会输出查询结果,除非你对它做一些事情,比如调用 toArray() 或使用 forEach() 迭代它

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多