I am passing a mongo cursor called resources
to this function. I want to restructure the resources by creating an empty object and using bracket notation to save the resources to the object. But it doesn’t take — I simplified my code as much as I could to demonstrate how it is behaving completely differently than I would expect.
I don’t know why Mongo would be involved here because typeof r.id === string
, but I did want to mention that. Especially because, when I iterate through a different data structure with .forEach
, this is not a problem.
I am using Typescript.
const restructured_resources = async(resources: any, db: any) => {
let restructured_resources: any = {}
resources.forEach((r: any) => {
const id = r.id
restructured_resources[id] = "yo"
})
console.log(restructured_resources) //{}
})
2
Answers
Added the await keyword in front of the forEach function results in the object becoming populated with the desired key value pairs. This leads me to believe that iterating through a Mongo cursor with a
forEach
loop is not a normal synchronous task, and is queued after theconsole.log
statement.This should work, so if it isn’t, it’s probably an
async
problem.