Home > Back-end >  Why I can't access nested data from MongoDB collection like normal JSON file?
Why I can't access nested data from MongoDB collection like normal JSON file?

Time:09-02

so I try to fetch data from my MongoDB collection using mongoose and typescript.

Mongo DB collection

I can successfuly get fetched data but the problem I have is, that I can only access _id, season and avatar with syntax like {{response.season}} or {{response.avatar}}. Nested data inside avatar JSON object can be accessed only like it's dictionary {{response.avatar["transfer"]}} and I'm not sure why is that. I would like to access it like {{response.avatar.transfer}}, is it possible to do that ?

Fetching data from MongoDB using mongoose

export default async function run() {
      // 4. Connect to MongoDB
      await mongoose.connect(config.publicRuntimeConfig.MONGO_URI);
    
      const results = await User.findOne({
        'season': '123'
      })
    
      await mongoose.disconnect();
      return results
    }

Data I receive

 {
      "_id": "630fbca3d06e5e2f310ea540",
      "season": 123,
      "avatar": {
        "from_team_id": 1,
        "to_team_id": 2,
        "transfer": "asdasd",
        "type": "dasdasd",
        "date": "asdasd",
        "amount": "asdasd",
        "player": {
          "player_id": 12,
          "country_id": 412,
          "display_name": "asdasd",
          "nationality": "asdasd",
          "_id": "630fbca3d06e5e2f310ea542"
        },
        "_id": "630fbca3d06e5e2f310ea541"
      },
      "__v": 0
    }

I want to access data like this if it's possible

  <template v-for="transfer in transferData">
        {{transfer.avatar.amount}}
    </template>  

What I can do now is

 <template v-for="transfer in transferData">
        {{transfer.avatar["amount"]}}
    </template>  

Is it possible to do that?

CodePudding user response:

You can access all of the response objects properties by defining a type or interface and setting the response object as that type. I'd recommend defining a type for your avatar and player object and then one for the entire response that contains the avatar type you defined.

type response = {
"_id”:string;
avatar:Avatar
// The rest of your properties
}

type avatar = {
“from_team_id”:string;
player:Player;
// Rest of properties
}
  • Related