skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 the console.log statement.

    const restructured_resources = async(resources: any, db: any) => {
    
        const thing: any = {}
        await resources.forEach((resource: any) => {
            restructured_resources[resource.id] = "yo"
        })
    
        console.log(restructured_resources)
    

  2. This should work, so if it isn’t, it’s probably an async problem.

    const restructured_resources = (resources) => {
      let restructured_resources = {}
      resources.forEach((r) => {
        const id = r.id
        restructured_resources[id] = "yo"
      })
    
      console.log(restructured_resources) //{}
    
    }
    
    restructured_resources([{id: 1},{id: 2},{id: 3},{id: 4},{id: 15},]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search