简体   繁体   English

如何在一个 controller API 和 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中发出多个“查找”请求?

[英]How to make multiple “FIND” request inside one controller API in express and Mongoose?

I have one API to consult data from database.我有一个 API 来查询数据库中的数据。 So I want to make multiple "FIND" query on mongoose, join all the responses and send back the result from the query.所以我想在 mongoose 上进行多个“查找”查询,加入所有响应并将查询结果发回。 I am using Nodejs and Express to make the API and Mongoose.我正在使用 Nodejs 和 Express 制作 API 和 Mongoose。

exports.data = (req, res) => {
    //FIND ALL CONSULTATIONS FILTERED BY STATUS
    const result1 = Model.find({ status: 'STATUS1' }).exec(
        (err, item) => {
            if (err) {
                return res.status(400).json({
                    error: 'Erorr en STATUS1',
                });
            }
            
        }
    );
    const result2 = Model.find({ status: 'STATUS2' }).exec(
        (err, item) => {
            if (err) {
                return res.status(400).json({
                    error: 'Erorr en STATUS2',
                });
            }
        }
    );


    res.json({result1, result2})

};

something like that, but it does not work.类似的东西,但它不起作用。 How can I achieve that?我怎样才能做到这一点? Make just one API call and response, but in the controller ask for different data, make one object and send it back.只制作一个 API 调用和响应,但在 controller 中要求不同的数据,制作一个 object 并将其发回。

Your current problem is that node will start the first find, and before it's done it'll start the second find, and before either of those are done it'll send back the result which will likely be { result1: undefined, result2: undefined }您当前的问题是节点将开始第一次查找,在它完成之前它将开始第二次查找,并且在其中任何一个完成之前它会发回可能是{ result1: undefined, result2: undefined }

You need to wait for the result before you send it back.您需要等待结果才能发回。

Your options are callback-hell, promises or async-await.你的选择是回调地狱、承诺或异步等待。 Pick your poison.选择你的毒药。

// callback hell
Model.find({ status: 'STATUS1' }).exec((err, result1) => {
  if (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS1'
    })
  }
  Model.find({ status: 'STATUS2' }).exec((err, result2) => {
    if (err) {
      return res.status(400).json({
        error: 'Erorr en STATUS2'
      })
    }
    res.json({ result1, result2 })
  })
})

// Promises
exports.data = async (req, res) => {
  //FIND ALL CONSULTATIONS FILTERED BY STATUS
  const promise1 = Model.find({ status: 'STATUS1' }).exec()
  const promise2 = Model.find({ status: 'STATUS2' }).exec()
  Promise.all([promise1, promise2])
    .then(([result1, result2]) => {
      res.json({ result1, result2 })
    })
    .catch(err => {
      return res.status(400).json({
        error: 'Erorr en STATUS2'
      })
    })
}

// Async Await
exports.data = async (req, res) => {
  //FIND ALL CONSULTATIONS FILTERED BY STATUS
  let result1
  let result2
  try {
    result1 = await Model.find({ status: 'STATUS1' }).exec()
  } catch (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS1'
    })
  }
  try {
    result2 = await Model.find({ status: 'STATUS2' }).exec()
  } catch (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS2'
    })
  }
  res.json({ result1, result2 })
}

None of the code above has been tested.上面的代码都没有经过测试。 It's just to give you a rough idea.这只是给你一个粗略的想法。

While promises looks cleaner here, I almost always opt for using async/await when I can.虽然 promise 在这里看起来更干净,但我几乎总是尽可能选择使用 async/await。 And since this is express, it makes sense to use express style error handler (and factor out the try-catches) which would make async-await look much cleaner.由于这是 express,因此使用 express 样式的错误处理程序(并排除 try-catch)是有意义的,这将使 async-await 看起来更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM