【发布时间】: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