I am trying to execute mongodb find query in a loop. I have an object with some properties. The value of each property will be checked in the mongodb to get its updated value. Once all the property values are updated, i want to perform some other actions.
But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData ) is getting executed and its throwing some error,since i dont have the updated values.
Thanks in advance for any help to solve this issue or any better methods for achieving this result.
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
}