I have the following JSON Object, which is the result of a loopback model (Classifications), with a relationship with another model (Labels).
My call to get the classifications is:
modClassification.findOne({
where: { id: classificationid },
include: 'labels' },
function( err, classification ){ ...
And this returns classification with something like
{ id: 'b01',
title: 'population',
country_id: 1,
labels:
[ { column_id: 'b1',
classification_id: 'b01',
classification_title: 'population',
dsporder: 1,
label: 'Total_Persons_Males',
country_id: 1,
id: 1 },
{ column_id: 'b2',
classification_id: 'b01',
classification_title: 'population',
dsporder: 2,
label: 'Total_Persons_Females',
country_id: 1,
id: 2 } ] }
which is what I would expect.
I now need to loop over the labels and access it's properties, but this is where I am stuck.
classification.labels[0] = undefined..
I have tried looping, each and whatever I can find online, but can't seem to get to each labels properties.
Can someone tell me what I am doing wrong/need to do?
Thanks
When you are including related models inside a findOne call, you need to JSONify the result before accessing the related records:
classification = classification.toJSON()
Then you should be able to access the included label items as you expect.
See https://docs.strongloop.com/display/public/LB/Include+filter, specifically the "Access included objects" section.
Note this does not work the same when you retrieve more than one result in an array. In that case you'll need to perform toJSON() on each item in the array.
Related
I need get a products which under Category but with a limit of products item for paginate purpose. I am use strapi headlessCMS for my backend. i will query it from "slug" in category. And then it will return collection as below code, but i need a LIMIT for my products list.
Since Strapi is use bookshelf.js in sql. i have tried it as exmaple 2 below. I am bad in handle data, hope someone sharing idea how to do or give some solution for me. Appreciate =).
If you know in raw sql statement, please sharing with me. I'll do the search for it. The important part is given a logically idea how to do with data. So, my brain has the map can do the searching. Thanks.
Model relationship:
Category hasMany Products
Example 1
const res = await strapi.query("category").findOne({ slug });
// return
{
id: 2,
slug: 'slug-string'
....
products: [
{
id: 1,
name: 'Ice Cream',
category: 2
},
{
id: 2,
name: 'Bread',
category: 2
},
....
{
id: 100,
name: 'Paper',
category: 2
}
]
}
Example 2: i guess this is bad practice ya? Because it query all products, the better way i think is example 1.
const Product = strapi.query("product").model;
const result = await Product.query((qb) => {
qb.where("category", 2);
}).fetchPage({
pageSize: 1,
page: start, // start is a number, it will pass from front end query page=2
});
I want to return a page with JSON server which is (https://github.com/typicode/json-server)
Currently, JSON Structure is looking like:
records :[
{
id: '2',
name: 'k',
},
{
id:'3',
name:'j'
}
]
I am able to return the records with pagination as GET /records?_page=1&_limit=10. After which I have changed the structure of JSON into:-
items:{
pageCount: 3,
records :[
{
id: '2',
name: 'k',
},
{
id:'3',
name:'j'
}
]
}
Now I want to do GET /records?_page=1&_limit=10 where I expect to return page 1 with 10 records and PageCount along with it.
If you follow closely the JSON server documentation, it says you can use the Link header from the response where you get first, prev, next and last links.
I'm building a fake API with json-server and I came across a problem when passing a query. I can show the parameters of a relationship when I use _expand, but when it is a relationship within a child it does not work.
For example, I have this json that I access by passinghttp://localhost:3000/schedules:
{
id: 1,
date: "2020-04-25T14:20:00-03:00",
status: "Novo serviço",
usersId: 5,
providersId: 1,
servicesId: 1,
},
Now to show the relationship with the user I pass the following query:
http://localhost:3000/schedules?_expand=users
It returns as follows:
{
id: 1,
date: "2020-04-25T14:20:00-03:00",
status: "Novo serviço",
usersId: 5,
providersId: 1,
servicesId: 1,
users: {
id: 5,
name: "Carla Pedroso",
photo: "https://cdn.pixabay.com/photo/2016/01/19/17/48/woman-1149911_960_720.jpg",
rating: 5,
addressesId: 1,
},
},
Well, my question is how I can show the JSON of the addressesId, because I already tried using_expand but without success.
change the schedule property "usersId" to "userId",
should work with
http://localhost:3000/schedules?_expand=user
and the response should be something like that:
{
id: 1,
date: "2020-04-25T14:20:00-03:00",
status: "Novo serviço",
providersId: 1,
servicesId: 1,
userId: 5,
user: {
id: 5,
name: "Carla Pedroso",
photo: "https://cdn.pixabay.com/photo/2016/01/19/17/48/woman-1149911_960_720.jpg",
rating: 5,
addressesId: 1
}
}
With json-server you can add the parent and children of an element to the result, but it will only bring one level, so it will not bring grandparents or grandchildren's.
In your case instead of looking at the schedules you can look at the users and ask to expand the addresses and embed the schedules
http://localhost:3000/users?_expand=addresses&_embed=schedules
new to ember js, and working on an app using ember-data. If I test with same data using FixtureAdapter, everything populates in the html template ok. When I switch to RESTAdapter, the data looks like it's coming back ok, but the models are not being populated in the template? Any ideas? Here's the code:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
})
});
App.Brand = DS.Model.extend({
name: DS.attr('string'),
numStyles: DS.attr('string'),
vendorId: DS.attr('string')
});
App.BrandsRoute = Ember.Route.extend({
setupController:function(controller){
},
model:function(){
return App.Brand.find();
}
});
And here is the data coming back, but not being inserted into the template!
returnValue: [{numStyles:1, name:Easton, vendorId:6043}, {numStyles:1, name:Louisville Slugger, vendorId:6075},…]
0: {numStyles:1, name:Easton, vendorId:6043}
1: {numStyles:1, name:Louisville Slugger, vendorId:6075}
2: {numStyles:1, name:Rawlings, vendorId:6109}
3: {numStyles:7, name:BWP Bats , vendorId:6496}
4: {numStyles:1, name:DeMarini, vendorId:W002}
status: "ok"
And here is the template:
{{#each brand in model.returnValue }}
<div class="brand-node"{{action select brand}}>
<h2>{{brand.name}}</h2>
<p>{{brand.numStyles}} Styles</p>
</div>
{{/each}}
Any help would be greatly appreciated! I'm not getting any errors, and the data seems to be coming back ok, just not getting into the template. Not sure if the returned dataset needs "id" param?
I am also using the Store congfig to alter the find() from plural to singular:
DS.RESTAdapter.configure("plurals", {
brand: "brand"
});
The way the API was written, its expecting "brand" and not "brands"... maybe its something to do with this??
Thanks in advance.
You have stated:
Not sure if the returned dataset needs "id" param?
Yes you are guessing right, you data coming back from the backend need's an id field set. And if the id field name is different then id you should also define this in ember like so:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
}),
serializer: DS.RESTSerializer.extend({
primaryKey: function (type) {
return '_my_super_custom_ID'; // Only needed if your id field name is different than 'id'
}
})
});
I suppose your Fixtures have an id defined thus it works, right?
Note: you don't need to define the id field at all explicitly, ember add's automatically the id field to a model, so your model is correct.
Here a website that is still a WIP but can be good reference for this conventions
and as stated there:
The document MUST contain an id key.
And this is how your JSON should look like for a collection of records:
{
"brands": [{
"id": "1",
"numStyles": "1",
"name": "Easton",
"vendorId" :"6043"
}, {
"id": "2",
"numStyles": "4",
"name": "Siemens",
"vendorId": "6123"
}/** and so on**/]
}
Note: as you have shown you JSON root is called returnValue this should be called brand or brands if you are not adapting the plurals. See here for reference for the JSON root I'm talking about.
Hope it helps
I am trying to load some JSON, in which I store a lot of variables about some 100 anaesthetic drugs for pediatric patients.
The actual values get calculated before from patient's weight, age etc.:
Example:
var propofolInductionTitle = propofolName + ' ' + propofol0PercentConcentration + '- Induktion';
var propofol0InductionDosageMG = (Math.round(kg * 2 * 10) / 10) + ' - ' + (Math.round(kg * 5 * 10) / 10);
I then create my drug as a block of json consisting of the variables I need which are later to be replaced by the calculated values. I specifically try to avoid Strings in the JSON to allow for easier localization to english and french when all variables are defined in the math block.
var hypnotikaJSON = {
"thiopentalTitle": [
{"thiopentalBrandName": ""},
{"vialContentTitle": "thiopentalVialContent"},
{"solutionTitle": "thiopentalSolution"},
{"concentrationTitle": "thiopentalConcentration"},
{"dosageString": "thiopentalDosageString"},
{"atWeight": "thiopentalDosageMG"},
{"thiopentalAtConcentration": "thiopentalDosageML"}
],
"propofolInductionTitle": [
{"propofolInductionBrandName": ""},
{"propofolVialContentTitle": "propofolInductionVialContent"},
{"propofolSolutionTitle": "propofolSolution"},
{"propofolConcentrationTitle": "propofolInductionConcentration"},
{"propofolInductionDosageStringTitle": "propofolInductionDosageString"},
{"atWeight": "propofolInductionDosageMG"},
{"propofolAtInductionConcentration": "propofolInductionDosageML"}
],
"propofolSedationTitle": [
{"propofolSedationBrandName":""},
{"propofolVialContentTitle":"propofolSedationVialContent"},
{"propofolSolutionTitle":"propofolSolution"},
{"propofolConcentrationTitle":"propofolSedationConcentration"},
{"propofolSedationDosageStringTitle":"propofolSedationDosageString"},
{"atWeight":"propofolSedationDosageMG"},
{"propofolAtSedationConcentration":"propofolSedationDosageML"}
],
"laryngealMaskTitle": [
{"laryngealMaskSizeTitle":"laryngealMaskSize"},
{"laryngealMaskCuffSizeTitle":"laryngealMaskCuffSize"},
{"laryngealMaskBiggestETTTitle":"laryngealMaskBiggestETT"},
{"laryngealMaskBronchoscopeSizeTitle":"laryngealMaskBronchoscopeSize"}
]
};
My specific need is that the JSON reader has to give me the key AND value of each object as I need both to populate a template. The reason ist that the fields for the drugs are different in parts. Some have additional routes of administration so I have another key:value pair a different drug doesnt have. Some are given both as bolus and per drip, some arent. So no convenient json structure ist possible.
I found an answer by rdougan here that partly allowed me to do just that:
Model:
Ext.define('my.model.Drug', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'value']
}
});
Custom Json Reader:
Ext.define('Ext.data.reader.Custom', {
extend: 'Ext.data.reader.Json',
alias: 'reader.custom',
getRoot: function (data) {
if (this.rootAccessor) {
data = this.rootAccessor.call(this, data);
}
var values = [],
name;
for (name in data) {
values.push({
name: name,
value: data[name]
});
}
return values;
}
});
Store:
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'value'],
data: hypnotikaJSON,
autoLoad: true,
proxy: {
type: 'memory',
reader: {
type: 'custom'
}
}
});
Panel:
this.viewport = new Ext.Panel({
fullscreen: true,
layout: 'fit',
items: [{
xtype: 'list',
itemTpl: '<p class="description">{name}</p><p class ="values">{value}</p>',
store: store
}]
});
Unfortunately I'm a physician and no programmer, and after a lot of reading I cant find out to apply this to a nested JSON. The custom reader seems to only go for the first level.
I could do it without a reader, without a store with just a lot of plan html around each entry, that has proven to be very very slow though so I would like to avoid it while updating from Sencha Touch 1.1. and better do it right this time.
Could you please point me to a way to parse this ugly data structure?
Thank you
I don't know much about extending JSON readers, so just guessing, but maybe you are supposed override the 'read' method? Then you can go over the JSON as you wish
Also, if you have control over the JSON you should consider changing it.
Usually, the keys in JSON should be the same throughout all items in the array.
keys are not data, they are metadata.
So, if you do have different properties between different drugs, then something like this might be a solution:
[{
name: 'Propofol 1%',
properties: [
{title: 'induction', value: '22-56g'},
{title: 'Sedation', value: '22'},
etc.
]},
{name: 'nextDrug'}
etc..