Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simple CRUD get/put/post/delete APIs, but now I'm facing a more complex scenario where I need to retrieve children of a node based on a specific Mongoose query.

The data returned by Mongoose looks like this:

{“children”: [ {name: value, …}, {name: value, …} ] }  

It seems to be an array wrapped in an object, and I'm unable to modify this format from the Mongoose/backend side.

Vue and Quasar on the frontend require some of these values from Mongoose, but they expect them in a pure array format like this:

[ {name: value, ...}, {name: value, ...} ]

In addition to the data fetched from the backend, I also need to add new name:value pairs for Quasar's consumption.

While I can successfully see the children in Chrome Vue Tools after making the REST call from the Vue component's onLazyLoad method, there is an issue with mapping the response data to meet Vue/Quasar requirements.

Here is the problematic code snippet within the Vue component's onLazyLoad method:

onLazyLoad({ node, key, done, fail }) {
      let parent_id = node._id; 
      // Make REST call to fetch children of a parent node from Mongoose
      http
        .get("/baustoff/kinder/"+parent_id)
        .then(response => {
            // Return empty tree array if no children found
          if (response.data == null) {
            done([]);
            return;
          }
          // Processing to create a Vue/Quasar QTree array with data from the REST call
          // ISSUE LIKELY STARTS HERE!!!!!!!!!!!!!!!
          let children = response.data;
          let treeNodes = []; // Array to structure children as required by QTree
          for (let i = 0; i < children.length; i++) {
                 treeNodes[i] = {
                 fachlicherTyp: children[i].fachlicherTyp,
                 _id: children[i]._id,
                 lazy: true,
                 parent_id: parent_id, 
               };    
          }
          done(treeNodes); // Render the tree using Quasar/vue QTree
          this.treeChange++; // Indicate tree change to Quasar
          return null;
      })
        .catch(e => {
          console.log(e);
        });
    }, // /onLazyLoad()

The main problem lies in the fact that the code never enters the for loop because 'children.length' is undefined due to incorrect processing of the response data.

I am looking for a solution within the provided Vue code above as I anticipate encountering similar issues in the future.

Any suggestions on how to better structure the JSON output on the Mongoose side are also welcome, specifically eliminating the {"children:" } wrapper. The Mongoose query responsible for this is:

Baustoff
  .findById(req.params.baustoffId)
  .select('children -_id') 
  .populate('kinder','name baumKnotenTyp fachlicherTyp aktiv produkt') 
   .lean().exec ( (err, baustoff) => { callback(err, baustoff, res) })
};

Answer №1

It seems that donvis, coming from mongoose, is an object rather than an array with a length property.

To properly handle this data, you can follow this approach:

donvis.kinder.forEach(child => {
  treeNodes.push({
    fachlicherTyp: child.fachlicherTyp,
    _id: child._id,
    lazy: true,
    parent_id: parent_id,
  })
})

The use of forEach in the above code snippet enhances readability. If you need help understanding it, feel free to ask.

Additionally, note that I'm opting for treeNodes.push(...) instead of directly assigning values like treeNodes[i] = ... as this is considered a more conventional way to populate an array.

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

Revise and optimize the solution for an algorithm using JavaScript

I recently participated in a technical interview for a software development company. The question presented to me was as follows: Given an array of numbers (n), find two numbers that sum up to a target number (k) and display them. Example: Inpu ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result. Here is my scenario: In my form.html file: ...

Issue with the react-redux Provider

Whenever I run my basic program Index.js function test(state = []) { return state } const store = createStore(test); render( <Provider store = { store } > <App / > < /Provider > , document.getElementById('root') ...

Initializing the IBM Worklight JSON Store

Having trouble setting up a json store. During initialization, I encountered the following error: BAD_PARAMETER_EXPECTED_ALPHANUMERIC_STRING Any advice on how to fix this issue? ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...

Best methods for sorting through a JSON array using Python

Here is the JSON array I'm currently working with. I need to extract all objects where type=1. Original data: [ { "type": 1, "name" : "name 1", }, { "type": 2 "name" : "name 2 ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

Ensuring Consistent Headings While Scrolling

Imagine having headings structured like this: <h1 class="fixontop">heading 1</h1> content goes here. . . . long paragraph. <h1 class="fixontop">heading 2</h1> 2nd content goes here. . . . long paragraph. <h1 class="fixontop"> ...

Checkbox does not trigger onCheck event

I am facing an issue with a checkbox component from material-ui where the onCheck event is not firing. <Checkbox label="label" onCheck={onCheck} checked={currentDocument.ispublic} /> function onCheck() { currentDocument.ispublic = !current ...

transmit an extensive amount of data from a RESTful API

Dealing with a large number of records in a REST service can be challenging, especially when updating a local database with 180,000 records. What is the most effective approach for handling this operation? One potential solution could involve creating a t ...

Using jQuery to automatically select a specific radio button after the load() function is executed

I'm trying to dynamically load radio buttons into a div using the JQuery load() function. However, I'm facing an issue when it comes to checking a specific radio button by its value. The problem is that the code doesn't seem to be working w ...

What are some effective strategies for sharing information in JavaScript?

I have an ASP.NET website and I need to pass information to JavaScript for some tasks. Currently, I am using the following method: <script type="text/javascript"> var userHasMicrositePhoto = '<%=hasMicrositePhoto%>'; </script& ...

Guide to utilizing an Ajax response object

Here is the code I am using to display data based on values selected from dropdowns: $("#botao-filtrar").click(function(){ $(".mask-loading").fadeToggle(1000); $.ajax({ url: 'datacenter/functions/filtraDashboardGeral.php', as ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Converting Buffers to Binary with JavaScript Node.js

I've been working with Node.JS Buffers to send and receive packets, but I'm struggling to figure out how to convert these buffers into binary representation. I attempted the following code snippet, but it didn't yield the expected results co ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

I am attempting to swap values within table cells using AngularJS. Would it be recommended to utilize ngBind or ngModel, or is there another approach that would

How can I make a table cell clickable in AngularJS to switch the contents from one cell to another, creating a basic chess game? I want to use angular.element to access the clicked elements and set the second clicked square equal to the first clicked using ...

Displaying content conditionally in Vue.js

I need assistance with displaying product lists for different companies in cards based on the selected section. Currently, the products are being displayed for all listed companies because the markup is the same across the page. Below is a snippet of my co ...