What is preventing me from accessing nested data in a MongoDB collection the same way I would in a standard JSON file?

When trying to fetch data from my MongoDB collection using mongoose and typescript, I am able to successfully retrieve the data. However, my issue lies in accessing nested data within the avatar JSON object. Currently, I can only access _id, season, and avatar with syntax like {{response.season}} or {{response.avatar}}. The nested data inside the avatar JSON object can only be accessed as if it were a dictionary, like this: {{response.avatar["transfer"]}}. I'm unsure why this is the case, as I would prefer to access it like {{response.avatar.transfer}}. Is there a way to achieve this?

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?

Answer №1

To access the properties of all response objects, you should create a type or interface and assign the response object to that type. It's advisable to create types for your avatar and player objects, as well as one for the complete response including the defined avatar type.

type fullResponse = {
"_id”:string;
avatar:Avatar
// Add other properties here
}

type Avatar = {
“from_team_id”:string;
player:Player;
// Add remaining properties
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to ensure that MongoClient is accessible globally on all pages within a Node.js REST API

After researching the official MongoDB documentation, I have successfully integrated mongoDB into my NodeJS REST API using the following connection code. const { MongoClient } = require("mongodb"); // Connection URI const uri = "mongodb+s ...

several mandatory fields in the json schema

In my schema, I have a required property that is dependent on an enumeration matching a certain value. This aspect of the schema is functioning as expected. "oneOf": [ { "not" : { "properties": { ...

Angular Typescript filter function returning an empty arrayIn an Angular project, a

I have a filtering function in Angular that is returning an empty array. Despite trying similar solutions from previous questions, the issue persists. The function itself appears to be correct. Any assistance would be greatly appreciated. gifts represents ...

Discovering arrays larger than the document size in MongoDB can be achieved by utilizing specific queries

I have a schema structured as follows: [ { id:"111" tags:[222,333,444,555] }, { id: "222" tags:[312,345,534] }, { id:"333" tags:[111,222,333,444,555] }, ] My goal is to identify all documents where the size of the tags ...

`MarkdownParser encounters bug in handling internal arrays during Newtonsoft DeserializeXNode process`

There is a JSON object with properties like: { "property1": "value1", "property2": "value2", "property3": ["value3","value4","value5"] } However, when attempting to convert it to XML using DeserializeXNode, the array is not preserved. <MyObj> ...

Creating personalized serialization for bson and JSON in Golang using mgo libraries

I am working with a custom type in Golang called Base64Data: type Base64Data []byte To facilitate unmarshalling a base64 encoded string into this type, I implemented the following method: func (b *Base64Data) UnmarshalJSON(data []byte) error { if le ...

Error: The defined success function is not present in the data object when using AngularJS

Trying to utilize JSON.parse with the following data: [{"id":"ABC123","provider_type":"Center","name":"Test1","phone":"03 2222 9999","mobile":"1111 123 123","email":"[email protected]","address":["3999, Victoria","Est Danvale","113 HD streed","Block D ...

Can the hash of a string be calculated while it already contains that hash?

As I was working today, I found myself attempting to generate a JSON document that looked like this: { 'a' : 1, 'b' : 2, 'hash' : (some hash value), } The challenge I encountered was setting the hash value to be ...

Verify whether the value of the Object matches the value of the string

Currently, I have a situation in ES6 where I am utilizing Vue.js for the current module. The task at hand is to verify if a specific string value exists within an array object. let obj1 = [{name: "abc ced", id: 1}, {name: "holla' name", i ...

Enable an object to be of specific types within a Swagger definition

Currently, I am working on defining an API and one of the fields is named "payload". Previously, this field was defined as "type": string in our Swagger documentation. However, we have noticed that the payload data now has a structured format. Specifi ...

The correct way to convert an object to JSON in Angular 2 using TypeScript

I am currently in the process of developing a simple CRUD application using Angular 2 that will allow me to manage products. The issue I am facing is with implementing the post method to create a new product. My backend is built on an ASP.NET Web API frame ...

Absolute imports in create-react-app do not function properly when using yarn v2 workspaces alongside typescript

I am currently utilizing yarn v2 workspaces, and within my workspaces, I have a frontend project built using create-react-app / react-scripts. My goal is to enable absolute imports in the frontend application so that I can simply do things like import Butt ...

The Angular error appears when attempting to access data that is undefined, specifically the property 'color'

Trying to fetch information from a locally stored file using Angular 4 but encountering an issue. Here is the data extracted: { "color": "blue" } Below is the relevant code snippet from the component.ts file: import { Component, OnInit } from ...

Creating an element in JavaScript with a designated ID is a

I'm working on creating a JavaScript array that holds 3 elements: var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] To iter ...

The dropCollection function is failing to delete the collection

Version numbers: mongoose 4.0.3, node 0.10.22, mongod db version 3.0.1 I've been attempting to drop a collection using Mongoose, but I'm encountering issues. execute: function() { return Q(mongoose.connect('mongodb://127.0.0.1:27017/te ...

The issue of Spring's @RequestBody failing to map to a custom Object

My custom Object, named ExampleObject, contains a org.json.JSONObject as a mongo query. public class ExampleObject { private JSONObject query; private String[] projections; private Number limit; // Constructors, getters and setters } In my REST contro ...

Python raised a "ValueError" indicating that when all scalar values are used, an index must be passed

After running the Python code to retrieve cryptocurrency closing prices from their inception with a list of tickers, I encountered a ValueError when I modified the code. def CryptoDataCSV(symbol, frequency): #Params: String symbol, int frequency ...

Transforming intricate JavaScript objects into JSON format using Node.js

Currently, I am engaged in a web scraping project and my goal is to construct a JSON object from the gathered data. Below is an outline of the steps I am taking to achieve this: var submitButton = driver.findElement(By.className('btn btn-primary& ...

Creating a parameterized default route in Angular 2

These are the routes I've set up: import {RouteDefinition} from '@angular/router-deprecated'; import {HomeComponent} from './home/home.component'; import {TodolistComponent} from './todolist/todolist.component'; import { ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...