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) })
};