Can I use this callback result with Backbone? - backbone.js

I hope someone can help me as Ive been trying for well over a week to see if I can use this callback result to populate a Backbone model/Collection.
Specifically, I want to list the Area Name and the AreaGUID - I also want to get the total price from the PriceMatrix.
PriceMatrix aside - I'd even settle for the Area Name and AreaGUID as I would hopefully learn how to traverse this JSON, and make collections from its nested values.
JSON:
$esro.GenericCallBack: (
{
"CustomCallback": "getEventDescriptionCallback",
"ErrorDescription": "",
"EvalMe": "",
"HasError": false,
"Result": {
"__type": "EventItemEntity:#eSRO.Code.JSonEntities",
"Areas": [
{
"Area": {
"AreaGuid": "9fc8ae7e-2059-4eb6-8c6f-527f3a0ea5fc",
"AreaMapGuid": "97a511ac-6b36-4223-9a08-5e099ebcd6ee",
"DefaultSeatingType": 10,
"GADefaultSettings": {
"Capacity": 10000,
"PriceLevelGuid": null,
"Restrictions": null
},
"Name": {
"Value": "Balc Fest 2013 Murmur"
},
"NameForReports": {
"Value": "Balc Fest 2013 Murmur"
},
"Ordinal": 0,
"ParentHallGuid": "b4df2722-fe70-4b03-bf9b-4a35286b1330",
"StandId": null,
"StandName": null
},
"AreaMap": {
"AreaMapGuid": "97a511ac-6b36-4223-9a08-5e099ebcd6ee",
"DescriptionLevel": 1,
"GASettings": null,
"GateCombinations": null,
"IncludedInMultipleVersions": false,
"Name": {
"Value": "Balc Fest 2013 Murmur"
},
"NumberOfSeats": 180,
"ParentAreaGuid": "9fc8ae7e-2059-4eb6-8c6f-527f3a0ea5fc",
"SeatingType": 20,
"Sectors": null,
"Status": 20,
"TurnstileCombinations": null,
"PriceLevelIds": [
"7ec859f6-2294-4b0f-b57a-9fa120c221a6",
"5112ea83-0880-4785-b93c-21e18c7a667b"
]
},
"Connector": {
"AreaLevelViewXaml": null,
"AreaMapGuid": "97a511ac-6b36-4223-9a08-5e099ebcd6ee",
"BackgroundImageIds": null,
"BestAvailableReservation": true,
"HallLevelViewXaml": "<Properties><Width>770</Width><Height>185</Height><X>0</X><Y>0</Y><Angle>0</Angle><Xaml /><AreaLabel /><StageSide /><IfShowLabel /></Properties>",
"Ordinal": 1,
"ParentVersionGuid": "b0352f6b-056d-4577-b3c1-c0ae8773bbb5",
"StaticViewXamls": null,
"ViewFromAreaImageId": null
},
"DependencyTags": [
"AreaMap=97a511ac-6b36-4223-9a08-5e099ebcd6ee",
"SeatingPlan=0aaa76eb-0b49-4ab7-9ef7-767b8400fb11",
"Area=9fc8ae7e-2059-4eb6-8c6f-527f3a0ea5fc;SeatingPlan=0aaa76eb-0b49-4ab7-9ef7-767b8400fb11",
"Show=37f6bcd8-c63c-4967-9982-3c3ae4c204e4",
"Area=9fc8ae7e-2059-4eb6-8c6f-527f3a0ea5fc;Show=37f6bcd8-c63c-4967-9982-3c3ae4c204e4",
"HallVersion=b0352f6b-056d-4577-b3c1-c0ae8773bbb5",
"Area=9fc8ae7e-2059-4eb6-8c6f-527f3a0ea5fc;HallVersion=b0352f6b-056d-4577-b3c1-c0ae8773bbb5"
],
"ImageUris": []
},
{
"Area": {
"AreaGuid": "063b1dad-e789-4857-852f-5e733fa84865",
"AreaMapGuid": "6c716990-9686-4304-a015-4db450f2fbd5",
"DefaultSeatingType": 10,
"GADefaultSettings": {
"Capacity": 1078,
"PriceLevelGuid": null,
"Restrictions": null
},
"Name": {
"Value": "ORCH Fest 2013 Murmur"
},
"NameForReports": {
"Value": "ORCH Fest 2013 Murmur"
},
"Ordinal": 0,
"ParentHallGuid": "b4df2722-fe70-4b03-bf9b-4a35286b1330",
"StandId": null,
"StandName": null
},
"AreaMap": {
"AreaMapGuid": "6c716990-9686-4304-a015-4db450f2fbd5",
"DescriptionLevel": 1,
"GASettings": null,
"GateCombinations": null,
"IncludedInMultipleVersions": false,
"Name": {
"Value": "ORCH Fest 2013 Murmur"
},
"NumberOfSeats": 425,
"ParentAreaGuid": "063b1dad-e789-4857-852f-5e733fa84865",
"SeatingType": 20,
"Sectors": null,
"Status": 20,
"TurnstileCombinations": null,
"PriceLevelIds": [
"7ec859f6-2294-4b0f-b57a-9fa120c221a6",
"5c9fa97b-c47c-463a-8da4-78956a241e5e",
"5112ea83-0880-4785-b93c-21e18c7a667b",
"01b28b26-b09c-46c3-b75a-02331c1231f9",
"e717cf91-986d-486d-b533-1309123fbf78"
]
},
"Connector": {
"AreaLevelViewXaml": null,
"AreaMapGuid": "6c716990-9686-4304-a015-4db450f2fbd5",
"BackgroundImageIds": null,
"BestAvailableReservation": true,
"HallLevelViewXaml": "<Properties><Width>770</Width><Height>185</Height><X>0</X><Y>195</Y><Angle>0</Angle><Xaml /><AreaLabel /><StageSide /><IfShowLabel /></Properties>",
"Ordinal": 2,
"ParentVersionGuid": "b0352f6b-056d-4577-b3c1-c0ae8773bbb5",
"StaticViewXamls": null,
"ViewFromAreaImageId": null
},
"DependencyTags": [
"AreaMap=6c716990-9686-4304-a015-4db450f2fbd5",
"SeatingPlan=0aaa76eb-0b49-4ab7-9ef7-767b8400fb11",
"Area=063b1dad-e789-4857-852f-5e733fa84865;SeatingPlan=0aaa76eb-0b49-4ab7-9ef7-767b8400fb11",
"Show=37f6bcd8-c63c-4967-9982-3c3ae4c204e4",
"Area=063b1dad-e789-4857-852f-5e733fa84865;Show=37f6bcd8-c63c-4967-9982-3c3ae4c204e4",
"HallVersion=b0352f6b-056d-4577-b3c1-c0ae8773bbb5",
"Area=063b1dad-e789-4857-852f-5e733fa84865;HallVersion=b0352f6b-056d-4577-b3c1-c0ae8773bbb5"
],
"ImageUris": []
}
],
"Id": "0aaa76eb-0b49-4ab7-9ef7-767b8400fb11",
"Pricing": {
"PriceLevelAxis": [
{
"key": "7ec859f6-2294-4b0f-b57a-9fa120c221a6",
"value": "C Price"
},
{
"key": "5112ea83-0880-4785-b93c-21e18c7a667b",
"value": "B Price"
},
{
"key": "5c9fa97b-c47c-463a-8da4-78956a241e5e",
"value": "W/C Wheel chair** C Price"
},
{
"key": "01b28b26-b09c-46c3-b75a-02331c1231f9",
"value": "W/C Wheel chair** B Price"
},
{
"key": "e717cf91-986d-486d-b533-1309123fbf78",
"value": "A Price"
}
],
"PriceMatrix": [
[
{
"ListPrice": "<Money amount=\"25\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>",
"PriceModifiers": null,
"TotalPrice": "<Money amount=\"25\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>"
},
{
"ListPrice": "<Money amount=\"40\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>",
"PriceModifiers": null,
"TotalPrice": "<Money amount=\"40\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>"
},
{
"ListPrice": "<Money amount=\"25\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>",
"PriceModifiers": null,
"TotalPrice": "<Money amount=\"25\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>"
},
{
"ListPrice": "<Money amount=\"40\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>",
"PriceModifiers": null,
"TotalPrice": "<Money amount=\"40\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>"
},
{
"ListPrice": "<Money amount=\"55\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>",
"PriceModifiers": null,
"TotalPrice": "<Money amount=\"55\" currencyCode=\"\" xmlns=\"http://foundation.toptix.com/2007\"/>"
}
]
],
"PriceModifierDescriptions": [],
"PriceTypeAxis": [
{
"key": "5ea4520c-d647-4a8c-b392-3f52910396d4",
"value": "FULL"
}
]
},
"SeatingTypeEnum": [
{
"key": "GA",
"value": 10
},
{
"key": "BA",
"value": 20
}
],
"ShowName": "Murmurs"
}
}
)
Model and Collection currently:
Entities.Area = Backbone.Model.extend({
defaults: {
Id: '',
AreaGuid:'',
AreaMapGuid: '',
AreaNameValue: '',
DefaultSeatingType: '',
PriceLevelIds: '',
MinPriceLevelIds: '',
MaxPriceLevelIds: '',
SeatingPlan: '',
BestAvailableReservation: '',
PriceLevelAxis: '',
PriceMatrix: '',
ShowName: '',
FacilityFee: '',
ServiceFee : '',
SeatPriceTotal : ''
Collection:
Entities.AreaCollection = Backbone.Collection.extend({
initialize: function() {
this.on('all', function(e) { console.log("Area event: " +e); });
},
url: "./murmurs.json",
model: Entities.Area,
parse : function(response){
return response.Result;
}
});
Please help if you can - and thanks!

you can have a straightforward hierarchical design like this ...
var RootModel = Backbone.Model.extend({
default:
{
"CustomCallback": "",
"ErrorDescription": "",
"EvalMe": "",
"HasError": false,
"Result": null
}
});
var ResultModel = Backbone.Model.extend({
default:
{
"__type": "",
"Areas": []
}
});
var AreaCollection = Backbone.Collection.extend({
model: areaDetailsModel
});
var AreaDetailsModel = Backbone.Model.extend({
default:
{
"Area": null,
"AreaMap": null,
"Connector": null
}
});
var AreaModel = Backbone.Model.extend({
default:
{
"AreaGuid": "",
"AreaMapGuid": "",
"DefaultSeatingType": 0,
"GADefaultSettings": null,
"Name": "",
"NameForReports": "",
"Ordinal": 0,
"ParentHallGuid": "",
"StandId": null,
"StandName": null
}
});
var AreaMapModel = Backbone.Model.extend({
default:
{
"AreaMapGuid": "",
"DescriptionLevel": "",
"GASettings": null,
"GateCombinations": null,
"IncludedInMultipleVersions": false,
"Name": "",
"NumberOfSeats": 0,
"ParentAreaGuid": "",
"SeatingType": 0,
"Sectors": null,
"Status": 0,
"TurnstileCombinations": null,
"PriceLevelIds": []
}
});
....
Then, you can assign your callback result to the rootModel.
var rootModel= new RootModel("your callback to JSON");
var resultModel = new ResultModel(rootModel.get("Result"));
var areas = new AreaCollection(resultModel.get("Areas"));
var areaDetail = areas.at(0);
var area = new AreaModel(areadetail.get("area");
...

I have not tried it but this may work.
var area_detail_model = Backbone.Model.extend({
defaults: {
AreaGuid: null,
AreaMapGuid: null
}
});
var area_map_model = Backbone.Model.extend({
defaults: {
AreaMapGuid: null,
DescriptionLevel: null
}
});
var area_model = Backbone.Model.extend({
defaults: {
Area: new area_detail_model(),
AreaMap: new area_map_model(),
Connector: [] // can declare a model for connector also
DependencyTags: [] // when using an array we can write bb_obj.get('Attr').ArrayItemName
},
parse : function(response){
// at this point only area models exist, i.e from area collection each area model
// is passed to this parse method
response.Area = new area_model(response.Area);
response.AreaModel = new area_map_model(response.AreaModel);
return response;
}
});
var area_collection = Backbone.Collection.extend({
model: area_model,
url: '/Areas',
parse : function(response){
return response; // place a break point and check out the contents of response
}
});
var result_model = Backbone.Model.extend({
defaults: {
Areas: new area_collection(),
Id: null,
Pricing: null,
},
url: '/GetResults',
parse : function(response){
response.Result.Areas = new area_collection(response.Result.Areas);
return response.Result; // this will return only the Result section from your JSON
}
});
var result_obj = new result_model();
result_obj.fetch();
So when the response is fetched then the result_model parse function will only pick Result from JSON and then we create a collection out the areas and the corresponding parse for each collection and method will be called in order. Let me know if it works.

Related

Improve reusability of my data transformation functions

I have currently done with my code transformation on my api data by its roleId.
However, I need to display another view which will group the data according to which projectId the users are in.
I can simply copy and paste and create another one for projectIds data transformation, however, I feel that my approach may be messy and not easily reusable.
So I would like to ask if there is a better way to do this?
Because i cannot simply swap roleIds in the function to projectIds by putting rolesId or projectIds in a variable to be reused in the function.
Can anyone help me please ?
Code for the api data transformation to dislay in ant design tree data table:
let apiData = [
{
email: "alyssayo#xxx.com",
permissionIds: null,
roleIds: ["raa", "baa", "caa"],
projectIds: ["1aa", "3aa"]
},
{
email: "chiuewww#xxx.com",
permissionIds: null,
roleIds: ["baa", "caa"],
projectIds: ["1aa", "2aa", "3aa"]
},
{
email: "lalaqq#xxx.com",
permissionIds: null,
roleIds: ["caa"],
projectIds: ["1aa"]
},
{
email: "sqssq#xxx.com",
permissionIds: null,
roleIds: [],
projectIds: []
}
];
//Isolate and transform data by roleId
const transData = apiData.reduce((arr, item) => {
let formatted = item.roleIds.map((id) => {
return {
roleIds: id,
children: [{ ...item, roleIds: id }]
};
});
return [...arr, ...formatted];
}, []);
//Group transformed data by roleIds
const findMatch = (arr, roleIds) =>
arr.find((item) => item.roleIds === roleIds);
const groupArray = (originalArr) => {
return Array.isArray(originalArr)
? originalArr.reduce((previousObj, obj) => {
if (findMatch(previousObj, obj.roleIds)) {
findMatch(previousObj, obj.roleIds).children.push(...obj.children);
} else {
previousObj.push(obj);
}
return previousObj;
}, [])
: "Need an array";
};
//Call the group roleId function on transformed data by roleId
const userRoledata = groupArray(transData);
//Add key to parent and children
let key = 1;
userRoledata.forEach((item) => {
item.key = key++;
item.children.forEach((child) => {
child.key = key++;
});
});
setData(userRoledata); //this will be dataSource for table rendering in ant design
What will the data transformed display when used as dataSource in ant design:
If grouped by roleIds:
[
{
"roleIds": "raa",
"children": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": "raa",
"projectIds": [
"1aa",
"3aa"
],
"key": 2
}
],
"key": 1
},
{
"roleIds": "baa",
"children": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": "baa",
"projectIds": [
"1aa",
"3aa"
],
"key": 4
},
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": "baa",
"projectIds": [
"1aa",
"2aa",
"3aa"
],
"key": 5
}
],
"key": 3
},
{
"roleIds": "caa",
"children": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": "caa",
"projectIds": [
"1aa",
"3aa"
],
"key": 7
},
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": "caa",
"projectIds": [
"1aa",
"2aa",
"3aa"
],
"key": 8
},
{
"email": "lalaqq#xxx.com",
"permissionIds": null,
"roleIds": "caa",
"projectIds": [
"1aa"
],
"key": 9
}
],
"key": 6
}
]
If grouped by projectIds:
[
{
"projectIds": "1aa",
"children": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": [
"raa",
"baa",
"caa"
],
"projectIds": "1aa",
"key": 2
},
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": [
"baa",
"caa"
],
"projectIds": "1aa",
"key": 3
},
{
"email": "lalaqq#xxx.com",
"permissionIds": null,
"roleIds": [
"caa"
],
"projectIds": "1aa",
"key": 4
}
],
"key": 1
},
{
"projectIds": "3aa",
"children": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": [
"raa",
"baa",
"caa"
],
"projectIds": "3aa",
"key": 6
},
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": [
"baa",
"caa"
],
"projectIds": "3aa",
"key": 7
}
],
"key": 5
},
{
"projectIds": "2aa",
"children": [
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": [
"baa",
"caa"
],
"projectIds": "2aa",
"key": 9
}
],
"key": 8
}
]
Define a transform function with 2 parameter. First the apiData, which is the data you want to transform and secondly the transformation_key which is a string of either roleIds or projectIds.
Within this function you first to generate an object with the different roleIds/projectIds as keys and for each key an array of all the items included.
To do so you make use of a reducer and loop over the items
apiData.reduce((obj, item) => {
if (!item[transformation_key]) return obj; // in case item[transformation_key] is null, you can skip the item an just return the item as is.
... // if not, we've to reduce over the array of roleIds/projectIds within the item as well.
}, {}) // {} is the new object (`obj` refers to this within the reducer)
Within each item we also have to loop over all the items in the roleIds/projectIds of that item, so we add a second/inner reducer.
// item[transformation_key] is the array of roleIds/projectIds within your item.
item[transformation_key].reduce((cur, id) => {
// `cur` is actually the same object as the `obj` from the outer reducer.
if (!cur[id]) cur[id] = [] // if the key/id doesn't excist yet on the object, we set it equal to an empty array.
cur[id].push({
...item,
[transformation_key]: id
}) // we push the item to the array (using the spread operator and updating the value for the `transformation_key` within the item.
return cur // you must return the object `cur`.
}, obj) // we pass to `obj` from the outer reducer into the inner reducer.
This will generate an object like
const transformedObject = {
[roleIds/projectIds] : [
... all the children
]
}
next we map the ids to the required output
return Object.keys(transformedObject).map(key => {
return {
[transformation_key]: key,
children: transformedObject[key]
}
})
To summarize
function transform(apiData, transformation_key) {
if (!(transformation_key == 'roleIds' || transformation_key == 'projectIds')) throw new Error("Choose either 'roleIds' or 'projectIds' as a transformation_key")
const transformedObject = apiData
.reduce((obj, item) => {
if (!item[transformation_key]) return obj;
return item[transformation_key].reduce((cur, id) => {
if (!cur[id]) cur[id] = []
cur[id].push({
...item,
[transformation_key]: id
})
return cur
}, obj)
}, {});
return Object.keys(transformedObject).map(key => {
return {
[transformation_key]: key,
children: transformedObject[key]
}
})
}
const transDataByRoleIds = transform(res.data, 'roleIds')
const transDataByProjectIds = transform(res.data, 'projectIds')

How to reduce aggregration time mongo db

I have written this query to aggregate data
db.attendancesCollection.aggregate([
{
'$match': {
'Date': { "$gte": start_date, "$lte": end_date },
'Location': found_location["locationName"],
'locationId': { '$exists': True },
'workerType': workerType
}
},
{
"$group": {
'_id': {
'employeeId': '$employeeId',
'workerId': '$workerId',
'workerFullName': '$workerFullName'
},
'dailyPointsArray': {
'$push': {
'Date': '$Date',
'createdAs': '$createdAs',
'Points': '$shiftPoints',
'inTime': '$inTime',
'outTime': '$outTime',
}
},
'total_shift_points': { '$sum': '$shiftPoints' },
'total_duration': { '$sum': '$duration' },
}
},
{
'$addFields': {
'Location': found_location["locationName"],
}
},
{
'$lookup':
{
'from': "users",
'localField': "_id.employeeId",
'foreignField': "_id",
'as': "userInfo"
}
}
])
There is no issue in running this query, I am getting desired data, but the problem lies in the execution time of the query, it takes about 20-30 secs for that, there are about 500,000 documents in attendance collection where I am performing aggregation & 1000 docs in user Collection where I am performing a lookup, what can I do to reduce execution time
This is sample structure
{
"_id": {
"$oid": "60dd7d723fcb2eb7df248af3"
},
"workerId": "xxxx",
"workerFullName": "ARUN",
"workerType": "Employee",
"workerAadharCardNumber": "xxxxxxxxxx",
"Date": {
"$date": "2021-07-01T00:00:00.000Z"
},
"employeeId": {
"$oid": "60dd77c14524e6c116e1692c"
},
"Location": "HEAD OFFICE",
"sourceUnitType": null,
"duration": null,
"shiftPoints": null,
"createdAs": "ABSENT",
"ruleApplied": null,
"detections": [],
"locationId": {
"$oid": "60dd6d303da6c17209d5ef68"
},
"workerFaceRegistered": true
}

How to fetch data from json in angularjs Form

How to call the data from json in angularjs form without using backend. i have written this code and here m unable to find a way in last to get data from the json file. someone please help me to move forward from here.
code
$scope.count = $scope.newPreAuth.length;
};
//Delete newPreAuth - Using AngularJS splice to remove the preAuth row from the newPreAuth list
//All the Update newPreAuth to update the locally stored newPreAuth List
//Update the Count
$scope.deletenewPreAuth = function (preAuth) {
$scope.newPreAuth.splice($scope.newPreAuth.indexOf(preAuth), 1);
getLocalStorage.updatenewPreAuth($scope.newPreAuth);
$scope.count = $scope.newPreAuth.length;
};
}]);
//Create the Storage Service Module
//Create getLocalStorage service to access UpdateEmployees and getEmployees method
var storageService = angular.module('storageService', []);
storageService.factory('getLocalStorage', function () {
var newPreAuthList = {};
return {
list: newPreAuthList,
updatenewPreAuth: function (newPreAuthArr) {
if (window.localStorage && newPreAuthArr) {
//Local Storage to add Data
localStorage.setItem("newPreAuth", angular.toJson(newPreAuthArr));
}
newPreAuthList = newPreAuthArr;
},
getnewPreAuth: function () {
//Get data from Local Storage
newPreAuthList = angular.fromJson(localStorage.getItem("newPreAuth"));
return newPreAuthList ? newPreAuthList : [];
}
};
});
Json Code
PreAuth:
======================
URL:http://dev.xxx.com:8080/xxx/preAuth
TYPE:POST
X-Auth-Token t3Z10HGEiYFdzq9lGtr18ycdeAAXmWBEI64rQAJcAte6Ka8Tz96IAhuXHSgpiKufsd
{
"preAuth": {
"claimbId": "newPreAuth",
"claimbStatus": "new",
"patientInfo": {
"patientName": "name",
"gender": "Male",
"dob": 950639400000,
"age": 21,
"contactNumber": 9987654356,
"tpaMemberId": 950639400121,
"policyNumber": "ABC12615627",
"corporateName": "ABC",
"EmployeeId": "XYZ10232",
"otherInsurance": {
"isOtherInsurance": true,
"playerName": "xyx",
"details": "sdfdsafdsfdsf"
},
"familyPhysician": {
"isFamilyPhysician": true,
"physicianName": "fsdf"'c
"physicianContactNumber": 7878748728,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"isFamilyPhysician": false,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"medicalInfo": {
"illnessType": "cancer",
"clinicalFinding": "description",
"ailmentDuration": "2 months",
"ailmentHistory": "description",
"illnessCause": "alcohol",
"provisionalDiagnosis": [
{
"diagnosisName": "abc",
"diagnosisICDCode": "121423"
},
{
"diagnosisName": "xyz",
"diagnosisICDCode": "434543"
}
],
"differentialDiagnosis": [
{
"diagnosisName": "afasdbc",
"diagnosisICDCode": "12431423"
},
{
"diagnosisName": "fdxyz",
"diagnosisICDCode": "434sdf543"
}
],
"clinicalObservations": {
"BP": "120/80",
"CVS": "126",
"P.A.": "abc",
"R.S.": "aa",
"CNS": "dd",
"others": "others"
},
"maternityDetails": {
"maternityType": "G",
"L.M.P.": 950639400000,
"E.D.D.": 950639400000
},
"accidentDetails": {
"accidentCause": "xyz",
"accidentDate": 950639400000,
"isPoliceComplaint": true,
"firNumber": "asfsafds"
},
"pastIllness": [
{
"pastIllnessType": "Diabetes",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Hypertension",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Other",
"isPresent": false,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
}
]
},
"treatmentInfo": {},
"billingInfo": {},
"documents": [
{
"documentId": 12345,
"documentMetadata": {
"documentName": "discharge summary",
"date": 950639400000,
"version": "1.1",
"viewedStatus": false,
"link": "link to view/download document"
}
},
{
"documentId": 12346,
"documentMetadata": {
"documentName": "medical summary",
"date": 950639400000,
"version": "1.0",
"viewedStatus": true,
"link": "link to view/download document"
}
}
]
}
}
I created sample ,it worked this way
// Code goes here
var app = angular.module('app',[]);
app.controller('sample', function($scope,$http){
$scope.name = "advaitha";
$http.get('test.json').then(function(data){
console.log(data.data);
});
})
here is the plunker example
using HTML5 localStorage would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "kisun",
lastname: "rajot",
website: "https://www.kisun.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("empData", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("empData"));
Created a plunker based on your code am able save and retrieve the json data with your code. Please check here

how can i update multiple elements of an array in Mongodb,node js

I need to update my complaints array object elements by complaints._id here is my mongo document.
{
"_id": "570785f0752eab040f347a70",
"createdAt": "2016-04-08T10:20:32.606Z",
"updatedAt": "2016-04-08T10:20:32.606Z",
"bookingid": "5704bd7cbd881ba413274c06",
"specialInstruction": "no special instruction",
"complaints": [
{
"complaint": "head light is not working",
"_id": "570785f0752eab040f347a72",
"labour": 0,
"partCost": 0,
"part": [],
"acceptance": false,
"inspection": false,
"color": "#CE002D",
"status": "WAITING",
"estimate": 0,
"solution": "",
"problems": ""
},
{
"complaint": "clutch is not good condition",
"_id": "570785f0752eab040f347a71",
"labour": 0,
"partCost": 0,
"part": [],
"acceptance": false,
"inspection": false,
"color": "#CE002D",
"status": "WAITING",
"estimate": 0,
"solution": "",
"problems": ""
}
],
"__v": 0
}
I am trying this approach but it is not working what be do
funcs.updatecomplaints=function(request, reply){
var id=request.params.complaintid;
console.log('TESTING'+id);
CPS.findByIdAndUpdate(request.params.documentid, {complaints:{
$set: { status: "WAITING", color : "#CE002D",$where: _id=id}}},
{upsert:true}, function (err, booking) {
Booking.findById(id, function(err, newbooking){
if(err){
console.log('Errorrrr Occured'+JSON.stringify(err));
return reply(JSON.stringify(err)).code(500);
}else{
console.log('All Booking are---->>'+booking);
return reply(newbooking).code(200);
}
});
});
For your problem I suggest to use the simple update api and not the findByIdAndUpdate, cause you will not search by id but you will search by complaints._id, and then use the $ identifier to change only the needed element.
CPS.update({
"complaints._id": request.params.documentid
}, {
"$set": {
"complaints.$.status": "WAITING",
"complaints.$.color": "#CE002D"
}
}, function(err, booking) {
Booking.findById(id, function(err, newbooking) {
if (err) {
console.log('Errorrrr Occured' + JSON.stringify(err));
return reply(JSON.stringify(err)).code(500);
} else {
console.log('All Booking are---->>' + booking);
return reply(newbooking).code(200);
}
});
});

Yii2 return JSON format with array inside an array

I am trying to get these data below,
Table relations:
people(one) <---> (many) people_info (one) <---> (many) people_contact
in the following format,
people: {
p_id: 10,
p_price: 3.99,
people_info : [
{
pl_id: 3,
pl_state: 2,
pl_district: 6,
pl_latitude: 6.323434,
pl_longitude: 108.23499,
people_contact: [
{
plc_id: 2
},
{
plc_id: 1
}
]
},
{
pl_id: 2,
pl_state: 7,
pl_district: 12,
pl_latitude: 6.000434,
pl_longitude: 108.9910003,
people_contact: [
{
plc_id: 5
},
{
plc_id: 9
}
]
}
]
}
Currently with these controller codes,
class PeopleController extends Controller
{
public function actionPeople($params){
Yii::$app->response->format = Response::FORMAT_JSON;
....//some other codes//.....
$people= People::find()->select(['p_id', 'p_price'] )->where(['p_id' => $itemId])->one();
$info= PeopleContact::find()->with(['plPeople'])->asArray([])->all();
return array(
'people' => $people,
'info' => $info,
);
}
}
I got these,
"people": {
"p_id": "3",
"p_price": "32.42"
}, "locations": [{
"pl_id": "1",
"pl_people": "3",
"pl_title": "",
"pl_latitude": "6.16438700000000000000",
"pl_longitude": "102.28314649999993000000",
"pl_place": null,
"pl_premise": null,
"pl_street": "1",
"pl_area": "1",
"pl_postcode": "1",
"pl_district": "1",
"pl_state": "3",
"pl_country": 1,
"place": null,
"premise": null,
"street": null,
"area": null,
"postcode": null,
"district": null,
"state": null,
"country": "United Kingdom",
"contacts": [{
"plc_name": "joe",
"plc_phone": "123456",
"plc_email": null
}]
}]
}
How do I achieve it in the format mentioned at the top?
$output;
$people=People::find()->select(['p_id', 'p_price'] )->asArray()->all();
foreach($people as $person) {
$infos = PersonInfo::find()->where(['person_id' => $person->id])->asArray()->all();
foreach($infos as $info) {
$contacts = PersonContact::find()->where(['person_info_id' => $info->id])->asArray()->all();
foreach($contacts as $contact) {
$info['contacts'][] = $contact;
}
$person['info'][] = $info
}
$output['people'][] = $person
}
return $output;
You should loop through and fetch data like this: people > info > contact each next level relying on info fetched from the previous one. Then store it in the format you want such as demonstrated above.
This will output something like:
"people": [{
...
"info": [{
...
"contacts": [{
...
},{
...
}]
}]
},{
...
}]

Resources