0

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) //{}

})

  • perhaps `resources.forEach` never executes because `resources` is empty - did you check for that? - also, why `restructured_resources = async` since there's nothing asynchronous about it – Bravo Apr 21 '22 at 03:14
  • Yeah, `console.log(resources)` prints out a big cursor object. And `resources.forEach((r) => {console.log(resource.id})` prints out a long list of ids. I checked and they are all `typeof string`. – thornberry Apr 21 '22 at 03:17
  • But this helped me solve the problem because it is sort of correct -- at the time of the console.log statement, resources is not empty but I think that `restructured_resources` is. – thornberry Apr 21 '22 at 03:27
  • The cursor object returned by the MongoDB find method has various methods which can be applied on it. `forEach` is one of them. `toArray` is another. See this post about: [What is a cursor in MongoDB?](https://stackoverflow.com/questions/36766956/what-is-a-cursor-in-mongodb/68212051#68212051). – prasad_ Apr 21 '22 at 04:22

2 Answers2

0

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)
-1

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},]);
cSharp
  • 2,884
  • 1
  • 6
  • 23