Connecting Vue.js Frontend -> through Express, Node.js, Sequelize (API) endpoints. (PostgreSQL) - postgresql

I have worked through various tutorials to understand and implement the Api Calls (Endpoints), defining Getters, almost to the point where I can fully invoke CRUD operations through routes pointing to them accordingly.
I can create Foreign Keys through sequelize, which creates my PostgreSQL table perfectly
async showAll (req, res) {
try {
const products = await Product.findAll({
where: {}
})
res.send(products)
} catch (err) {
res.status(500).send({
error: 'An Error has occured trying to retrieve Products'
})
}
},
In Postman
When hitting my endpoint GET /principals
All the relevant products are also displayed
{
"id": 2,
"name": "Company B",
"telephoneNumber": "012 111 1111",
"address": "Betha Str\nBedrasDorp",
"logo": "",
"registrationNumber": "2020/123/1234",
"taxNumber": "123",
"monthEnd": 1,
"createdAt": "2020-01-31T09:29:39.692Z",
"updatedAt": "2020-01-31T09:29:39.692Z",
"products": [
{
"id": 18,
"stockCode": "U7U5U",
"nappiCode": "NULL",
"barCode": "NULL",
"description": "Silver",
"sysPrice": 297.43,
"image": "",
"createdAt": "2020-01-31T09:25:22.620Z",
"updatedAt": "2020-01-31T09:25:22.620Z",
"principalId": 2
},
My question
How do I display my Principal Name in a Vue component and not just the principalID as per sequelize created column on my postgreSQL DB.
My current section within products.vue
<script>
....
async mounted () {
// do request to list all products
this.products = (await ProductsService.showAll()).data
}
...
</script>
displaying the productId
....
<template
slot="items"
slot-scope="{ item }">
<td>{{ item.stockCode }}</td>
<td>{{ item.description }}</td>
<td class="text-xs-left"> {{ item.principalId }} </td>
</template>
...
How can I display the Principal - name from a foreign key constraint? Linked in my PostgreSQL table in the Vue component.
Please help!

I managed to sort it out.
You controller section should include.
async showAll (req, res) {
try {
const products = await Product.findAll({
where: {},
include: [
{
model: ParentName
}
]
})
res.send(products)
} catch (err) {
res.status(500).send({
error: 'An Error has occured trying to retrieve Products'
})
}
}
Your .vue component Script section
async mounted () {this.products = (await ProductsService.showAll()).data
}
And calling it in the Template Component within vue becomes easy
{{ props.item.Principal.name }}

Related

No data being returned from syncfusion querybuilder

I have a dataset that I want to build a query tool for so not being a web developer I turned to Syncfusion's QueryBuilder.
Using the exact code displayed here in their tutorial of local data for the App.vue and datasource.js. I made my webpage, when when entering conditions no data is returned to me. How can I get the data to be return when querying it?
We have checked your reported query. We have prepared Querybuilder sample using local data as demonstrated in the below code snippet.
App.vue
<template>
<div class="control-section">
<div class="col-lg-12 querybuilder-control">
<ejs-querybuilder
width="70%"
:rule="importRules"
:dataSource="dataSource"
>
</ejs-querybuilder>
</div>
</div>
</template>
<script>
import Vue from "vue";
import {
QueryBuilderPlugin,
dataSource,
} from "#syncfusion/ej2-vue-querybuilder";
Vue.use(QueryBuilderPlugin);
import { employeeData } from "/src/dataSource.js";
export default {
data: function () {
return {
dataSource: employeeData,
values: ["Mr.", "Mrs."],
importRules: {
condition: "and",
rules: [
{
label: "Employee ID",
field: "EmployeeID",
type: "number",
operator: "equal",
value: 1,
},
{
label: "Title",
field: "Title",
type: "string",
operator: "equal",
value: "Sales Manager",
},
],
},
};
},
};
</script>
For your reference, we have prepared a sample based on your requirement. Please check the below sample.
Sample: https://codesandbox.io/s/vue-template-forked-g62vv?file=/src/App.vue

Update single specific field only when using $ in embedded document Mongodb

Here's my snippet of code.
router.post(
"/chapter/officers/edit/:id/:c_id",
async (req, res) => {
try {
const updateChapter = await Council.findOneAndUpdate(
{ "chapters._id": req.params.c_id },
{
"chapters.$.officers": req.body,
}
);
if (!updateChapter) return res.status(404).json({ msg: "Not found" });
res.json("Edit Success");
} catch (error) {
res.status(500).json({ msg: error.message });
}
}
);
I am planning on updating only one specific field at a time BUT when I tried to send this JSON from Postman
{
"grandTriskelion": "sample"
}
The other filled in field values becomes an empty string. Heres an example of my res.json
"_id": "5fc9cbb7ba7e2e2430c9a4d8",
"name": "Maria Aurora",
"code": "MA",
"chapters": [
{
"officers": {
"grandTriskelion": "sample",
"deputyGrandTriskelion": "",
"masterWilderOfTheWhip": ""
},
"_id": "5fca014e49fa3f2910794bb8",
"name": "Maria Aurora Community Based"
}
],
I've hit a roadblock. I'm a beginner at MERN stack.

Problems with programmatically selecting node in jsTree on page start-up

I can't select a tree element on page start-up. There is a JSFiddle with the setup: https://jsfiddle.net/voltel/aszn3h46/
My data is JSON array:
const a_data = [
{
"id": "1296",
"text": "Disposable and Single-Use Medical Supplies",
"children": null
},
{
"id": "1275",
"text": "Implantables",
"children": [
{
"id": "1276",
"text": "Defibrillators, Implantable",
"children": null
},
{
"id": "1338",
"text": "Analysers, Laboratory In-Vitro Diagnostic, Clinical Chemistry, Manual",
"children": null
},
]}
];
// Rest of JavaScript code
const $tree = $("#display");
$tree.jstree({
'plugins' : [ "wholerow", "checkbox" ],
'core': {
data : a_data
},
'checkbox': {
three_state: false
},
});
//
// The problem: I can't select/check node with this id
const c_icd_device_type = "1338";
// show initial value
if (c_icd_device_type) {
console.log(`Request to select node with id ${c_icd_device_type}`);
const o_selected_node = $tree.jstree('get_node', c_icd_device_type);
console.log('Selected node: ', o_selected_node);
// Uncomment ONE of the following:
if (o_selected_node) {
$tree.jstree('select_node', o_selected_node, true);
} else {
$tree.jstree(true).select_node(c_icd_device_type);
}//endif
}//endif
Please, help select a node on start-up, and get rid of some suspicious errors in console (see JSFiddle).
Now, I understand from other questions on jsTree here on StackOverflow, that if wrap my code selecting an element in an event handler, it works. I don't quite understand why it is so complicated, provided there are no asynchronous calls. And if it's unavoidable, why not use Promise?
$tree.on('ready.jstree', function (e, data) {
console.log(`Request to select node with id ${c_icd_device_type}`);
const o_selected_node = data.instance.get_node(c_icd_device_type);
//const o_selected_node = $tree.jstree('get_node', c_icd_device_type);
console.log('Selected node: ', o_selected_node);
// Uncomment ONE of the following:
if (o_selected_node) {
$tree.jstree('select_node', o_selected_node, true);
} else {
$tree.jstree(true).select_node(c_icd_device_type);
}//endif
});
I don't see any errors in console on Chrome:
Your code is fine. It just that the tree isn't ready yet. If you wrap your existing code inside ready.jstree event, it'll work.
$tree.on('ready.jstree', function (e, data) {
// Copy line 38 onward and place your existing code here
});

Post to a mongoose schema with array of objects

I want to post some data to my mongo database.
However the structure of the schema confuses me about the implementation.
This is the schema:
var GraphSchema = new Schema({
nodes: [{id: String}],
links: [{source:String, target: String}]
});
This is what I've tried so far but it doesn't seem to working:
router.post('/graphs', (req, res) => {
const graph = new Graph();
graph.nodes = [{id: req.body.nodes.id}];
graph.links = [{source: req.body.source, target: req.body.target}];
graph.save((err) => {
if(err) return res.status(500).json({ message: 'internal error' })
res.json({ message: 'saved...' })
})
});
For example I want to achieve something like this as a final result:
{
"data": [
{
"nodes": [
{
"id": "root"
},
{
"id": "input"
},
{
"id": "component"
}
],
"links": [
{
"source": "component",
"target": "root"
}
]
}
]
}
I a testing the operation with Postman
I am in a kind of dead end regarding how to proceed so I hope you can hint me something!
in your creation of the object , creat it like this
router.post('/graphs', (req, res) => {
const graph = new Graph({
nodes:[{id:req.body.nodes.id}],
links:[{source: req.body.source, target: req.body.target}]
}); // you need to include your data inside the instance of the model when you create it that was the problem.. It should work fine now
In your code you don't actually create the array that you have defined in your schema. So tally with your schema like above and then save. below
graph.save((err) => {
if(err) {
res.status(500).json({ message: 'internal error' });
throw err;
}else{
res.send({ message: 'saved...' });
}
})
});
this is the way you have currently posted the question.. so the answer is valid for that, but I assume this should be sufficient enough for you to figure out what was the problem ..

DataTables Requested unknown parameter '1' for row 0, column 1 FeathersJs

I have featherjs app and trying to use datatables. I am using ajax datasource with configuration below:
$('#example').DataTable({
"ajax": {
"url": "<url-placeholder>",
"dataType": "json",
"cache": true, // this is to remove the '_' sent by datatables
"data": function(params) {
// Put additional parameters here
return params;
},
"dataSrc": function(result) {
var data = JSON.stringify(result.data);
console.log(data);
return data;
},
"columns": [
{ data: "_id" },
{ data: "name" },
{ data: "symbol" }
]
}
});
I have HTML like this
<table id="example">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Symbol</th>
</tr>
</thead>
</table>
The server returned this:
[{"_id":"5abdd8548d46ed03dcb0ce2c","name":"ABS-CBN","symbol":"ABS"},{"_id":"5abdd8548d46ed03dcb0ce2d","name":"AC PREF B2","symbol":"ACPB2"},{"_id":"5abdd8548d46ed03dcb0ce2e","name":"Asiabest Gorup","symbol":"ABG"},{"_id":"5abdd8548d46ed03dcb0ce2f","name":"AC PREF B1","symbol":"ACPB1"},{"_id":"5abdd8548d46ed03dcb0ce30","name":"Anchor Land","symbol":"ALHI"},{"_id":"5abdd8548d46ed03dcb0ce31","name":"Bogo Medellin","symbol":"BMM"},{"_id":"5abdd8548d46ed03dcb0ce32","name":"DAVINCI CAPITAL","symbol":"DAVIN"},{"_id":"5abdd8548d46ed03dcb0ce33","name":"FIRST METRO ETF","symbol":"FMETF"},{"_id":"5abdd8548d46ed03dcb0ce34","name":"IPeople","symbol":"IPO"},{"_id":"5abdd8548d46ed03dcb0ce35","name":"Manila Bulletin","symbol":"MB"}]
The datatables returning this error. And I have searched for answers for many hours now. I am stuck on this error
DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4
I think the problem is because you have the columns definition within the Ajax block - it should be outside:
$('#example').DataTable({
"ajax": {
"url": "<url-placeholder>",
"dataType": "json",
"cache": true, // this is to remove the '_' sent by datatables
"data": function(params) {
// Put additional parameters here
return params;
},
"dataSrc": function(result) {
var data = JSON.stringify(result.data);
console.log(data);
return data;
}
},
"columns": [
{ data: "_id" },
{ data: "name" },
{ data: "symbol" }
]
});
I don't believe that the cache and dataType options are supported by DataTables, but try removing those after moving the columns block first.