在Node.js中获取最新数据时遇到的问题

时间:2019-07-02 13:06:35

标签: javascript node.js

从MongoDB获取最新数据时,我遇到了问题。每3个小时,当我获取最新数据时,我就将数据推送到MongoDB上。

这是架构

var abc = new Schema({
    item_name: String,
    uploadedDate: String, //"6-29-2019"
    date : Date
});

获取最新数据 req.body.uploadedDate =“ 7-2-2019”字符串

router.post('/todayList', (req, res, next) => {
  abc.find({ "uploadedDate": { "$eq": req.body.uploadedDate} })
    .then(product => {
      let final = funct.duplicate(product, 'item_name'); here i am filter duplicate object 
      var result = [];
       final.forEach(comp => {
        abc.find({item_name": comp.item_name, "uploadedDate": { "$eq": 
    req.body.uploadedDate} }) // here i am fetching the latest uploaded data based on the item_name and pushing to the 'result'
        .sort({"date":-1})
        .limit(1)
        .exec((err, docs) => { 
          console.log(docs); //i am getting the latest data here
          result.push(docs);
         });
       })
       //but here the value of 'result' is empty array
      res.status(200).json({
        data: result
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

我无法找到为什么给出空数组的原因。请帮助我

1 个答案:

答案 0 :(得分:1)

for循环内的代码是异步的。 因此,在for循环中的查询完成运行之前,将以空结果发送响应。

在发送响应之前,您应该让代码等待查询完成运行。

router.post('/todayList', (req, res, next) => {
  abc
    .find({ uploadedDate: { $eq: req.body.uploadedDate } })
    .then(product => {
      let final = funct.duplicate(product, 'item_name')
      var promises = []
      final.forEach((err, documents) => {
        promises.push(
          new Promise((resolve, reject) => {
            if (err) return reject(err)
            abc
              .find({ item_name: comp.item_name, uploadedDate: { $eq: req.body.uploadedDate } })
              .sort({ date: -1 })
              .limit(1)
              .exec((err, docs) => {
                if (err) return reject(err)
                resolve(docs)
              })
          })
        )
      })

      Promise.all(promises).then(result => {
        res.status(200).json({
          data: result
        })
      })
    })
    .catch(err => {
      console.log(err)
      res.status(500).json({
        error: err
      })
    })
})