【问题标题】:How to execute mongodb find query in a loop in nodejs如何在nodejs的循环中执行mongodb find查询
【发布时间】:2020-05-31 21:52:05
【问题描述】:

我正在尝试循环执行 mongodb find 查询。 我有一个具有一些属性的对象。每个属性的值将在 mongodb 中检查以获取其 更新值。更新完所有属性值后,我想执行一些其他操作。

但是在获取更新的对象(updatedVehObj)之前,下一行代码(函数 updatedVehicleData ) 正在执行并抛出一些错误,因为我没有更新的值。

提前感谢您提供解决此问题的任何帮助或任何更好的方法来实现此结果。

const processVehData = async (vehData) => {
  const vehObj = {
    make: 'AUD',
    model: 'A12',
    type: 'S',
  }
  const updatedVehObj = await getDBMapping(vehObj)
  // Do some preocessing with the updated vehicle obj
  const processedDataRes = updatedVehicleData(updatedVehObj)
  return processedDataRe;
}

const getDBMapping = async (vehObj) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
    }
    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // Iterating every element in the object
      await dbo
        .collection(key)  // key name will be the collection name in mongodb
        .find({         
          code: vehObj[key],
        })
        .toArray()
        .then(result => {
          updatedVeh[key] = result[0] // Framing new object with updated values
        })
        .catch(err => {
          console.log(' Error in getting mapping', err)
        })
    }
    return updatedVeh;
    /*** Expected result
      updatedVeh = {
        "make": "AUDI",
        "model" : "A3 Auto",
        "type" : "Sedan"
      }
    ****/
  })
}

const updatedVehicleData = vehData => {
  // Do something
}

【问题讨论】:

    标签: node.js mongodb async-await


    【解决方案1】:

    您的问题来自MongoClient.connect()callback,在执行await getDBMapping(vehObj) 时,您不是在等待解决问题。

    此外,您在更新查询中结合了 awaitthen

    解决方案可能是在getDBMapping 函数中使用Promise

    const getDBMapping = async (vehObj) => new Promise((resolve, reject) => {
      let updatedVeh = {}
      MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
        if (err) {
          console.log('Error in connecting to DB')
          return reject(err); // reject is there is an error
        }
    
        const dbo = client.db('VehicleDataBase')
        for (const key of Object.keys(vehObj)) {
          // use try / catch instead of combined await / then
          try {
            const result = await dbo
              .collection(key)
              .find({         
                code: vehObj[key],
              })
              .toArray();
    
            updatedVeh[key] = result[0];
          } catch (err) {
            console.log('Error in getting mapping', err)
            // reject(err); => you can also reject here, but it could break batch update transaction
          }
        }
    
        return resolve(updatedVeh);
      })
    });
    

    【讨论】:

      【解决方案2】:

      根据您的问题“但是在获取更新的对象(updatedVehObj)之前,下一行代码(函数 updatedVehicleData )正在执行并抛出一些错误,因为我没有更新的值。” em>

      您必须在此函数之前编写相同的 async 和 await,

      const processedDataRes = await updatedVehicleData(updatedVehObj)
      
      const updatedVehicleData = async vehData => {
        // Do something
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 2018-05-15
        • 2020-04-03
        • 2018-07-19
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        相关资源
        最近更新 更多