【问题标题】:Nodejs mongdb query data using async/awaitNodejs mongodb 使用 async/await 查询数据
【发布时间】:2019-08-06 18:33:56
【问题描述】:

我正在使用节点模块mongodb v3.2.7,并使用express 来实现我的api

我使用callback。而且,效果很好

函数findItem

const findItem = function (id, callback) {
  if (db) {
    const collection = db.collection('transaction')
    collection.find({ user_id: id})
      .project({ ready: 1, online: 1, status: 1})
      .toArray(function (err, docs) {
        if (err) {
          callback(err)
        } else {
          callback(null, docs)
        }
      })
  }
}

我的 api

app.get('/', (req, res) => {
  try {
    if (req.query.user_id) {
      const contentType = 'application/json'

      res.set({ 'Access-Control-Allow-Origin': '*',
        'Content-Type': contentType })

      const user_id = parseInt(req.query.user_id, 0)
      findItem(user_id , function (err, docs) {
        if (err) {
          res.status(500).end()
          return res.send(err)
        }
        const data = processData(docs)
        console.log('data', data)
        return res.send(data)
      })
    } else {
      res.send()
    }
  } catch (ex) {
    console.log(ex)
  }
})

然后,我尝试使用async/await 而不是callback。但是,它不起作用。我犯了什么错误?

函数findItemAsyncAwait

const findItemAsyncAwait = async function (id) {
  if (db) {
    const collection = db.collection('transaction')
    var docs = await collection.find({ user_id: id })
      .project({ ready: 1, online: 1, status: 1})
      .toArray()
    return docs
  }
}

我改过的api

app.get('/', (req, res) => {
  try {
    if (req.query.user_id) {
      const contentType = 'application/json'

      res.set({ 'Access-Control-Allow-Origin': '*',
        'Content-Type': contentType })

      const user_id = parseInt(req.query.user_id, 0)
      const promiseDocs = findItemAsyncAwait(user_id)
      promiseDocs.then((docs) => {
        console.log('docs', docs) // <= docs [], docs is an empty array without any document
        const data = processData(docs)
        console.log('data', data)
        return res.send(data)
      }).catch((err) => {
        res.status(500).end()
        return res.send(err)
      })
    } else {
      res.send()
    }
  } catch (ex) {
    console.log(ex)
  }
})

我仍然卡在这个问题上。有人可以帮忙吗?

【问题讨论】:

    标签: node.js mongodb asynchronous async-await


    【解决方案1】:

    你要等待收藏

    const findItemAsyncAwait = async function (id) {
      if (db) {
        return await db.collection('transaction')
          .find({ user_id: id })
          .project({ ready: 1, online: 1, status: 1})
          .toArray()
      }
    }
    

    【讨论】:

    • 这不仅不起作用,还会引发eslint警告Redundant use of await on a return valuedocs 仍然是一个空数组
    • eslint 警告在大多数情况下是正确的 - 它应该是直接的return db.collection(),并且可以在没有async - more info here 的情况下声明该函数。至于功能方面,db.collection() 不带回调使用应该表现得像 Promise。
    • 使用回调方法,效果很好。所以,我认为const collection = db.collection('transaction')collection.find({ user_id: id})...这行没有问题
    • 试试console.log(db.collection('transaction')) - 如果这是一个Promise,你必须做const collection = await db.collection('transaction')
    • 它是一个对象,而不是一个 Promise。
    猜你喜欢
    • 2022-01-11
    • 2020-01-06
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2021-10-05
    相关资源
    最近更新 更多