1

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
}

2 Answers 2

2

Your problem came from the callback of MongoClient.connect(), when performing await getDBMapping(vehObj) you are not waiting for something to be resolved.

Also, you combined await and then on update queries.

A solution could be to use a Promise in getDBMapping function :

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);
  })
});
Sign up to request clarification or add additional context in comments.

Comments

0

As per your problem "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."

You have to write same async and await before this function,

const processedDataRes = await updatedVehicleData(updatedVehObj)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.