In my Angular app with a MongoDB/Node backend, I have been successfully iterating over an array of records and printing them to the view in a table layout - one line per object in the array.
Now I have a situation where I need to break out what was information on one line into three lines, based on info in a "subdata" object. A simplified version of the data looks like this:
data: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
subdata: {
a: "value a",
b: "value b",
c: "value c"
},
deleted: false
}
]
Rather than iterating once for each object in the "data" array, which I was doing before like this:
<tr *ngFor="let record of records.data | paginate: { id: 'results', itemsPerPage: 12, currentPage: getPageNumber(), totalItems: records.count }">
... I instead need to now print three lines - one for each of the values in the "subdata" object. But each of those lines needs to include the name, the birthDate, and the city that is part of the parent object.
From an architectural point of view, does it make it more sense to create a new backend endpoint, and populate the data in the format I want to iterate over it by (which would involve some repetition of props and values (name, birthDate, city, etc...), like this:
reOrgedData: [
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
a: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
b: value
deleted: false
},
{
name: {
first: "John,
last: "Smith
},
referred: true,
birthDate: date,
city: "New York",
createDate: date,
c: value
deleted: false
}
]
or is there a way I can iterate over this in its original data structure, but still break it out into three lines in the view?
My sense is that creating a custom endpoint with the data organized in the form I need is the way to go, even though that does involve some repetition. This approach makes for less hoops-jumping on the front-end. But I am curious for people's take on what would be the best approach in a scenario like this.
Related
I'm building a post request which will contain various info on each role. E.g in this trial, 'Data Analyst'.
In this position I want to have quite a few sources of data, including things like salary, education and skills.
However, I'm using recharts to visualise it, which means although I need a key, e.g Masters's degree, I also need a num value associated, such as below:
const educationData = [
{
degree: 'Masters',
A: 120,
},
{
degree: 'Bachelor',
A: 98,
},
{
degree: 'PhD',
A: 86,
},
{
degree: 'Industry',
A: 99,
},
{
degree: 'Associate',
A: 85,
}
];
I would like to store this inside my schema created:
const RolesPositionSchema = new mongoose.Schema(
{
title:{type:String, required: true, unique: true},
desc:{type:String, required: true},
skills:{type:Array, required: true},
salary:{type:Array},
education: {type: Array},
popularity: {type: Number},
reccomendations: {type: Array},
},
);
Within this I would like to store the 'educationData' into the DB. Happy to input it in manually for now. I just want to know how to structure my schema/data in the postman request.
E.g Input in "education", stored with "Masters:120", "Bachelor:98", "PhD:86" etc -> within the post request:
{
"title" : "Data Analyst",
"desc": "Using both internal and external data sources you will develop insights to identify trends and opportunities whilst highlighting areas or improvement to optimise member interaction. This is a proactive role where you will own how we interpret data, allowing you to provide valuable insight into the development and implementation of product, customer and channel strategies for our sales, retention, and acquisition goals.",
"skills":["SQL" ,"Excel", "Tableau", "PowerBI", "Python", "Azure", "AWS", "ETL"],
"education": ["INPUT AN ARRAY OF EDUCATION AND THEIR VALUES HERE!]
}
Thankyou!
You could modify first your payload into the format of schema.
Payload
const educationData = [
{
degree: 'Masters',
A: 120,
},
{
degree: 'Bachelor',
A: 98,
},
{
degree: 'PhD',
A: 86,
},
{
degree: 'Industry',
A: 99,
},
{
degree: 'Associate',
A: 85,
}
];
Process
const newEducations = educationData.map(education => {
return `${education.degree}:${education.A}`;
});
const storeRole = new RolesPositionSchema({
title: 'Data Analyst',
desc: 'Using both internal and external data sources you will develop insights to identify trends and opportunities whilst highlighting areas or improvement to optimise member interaction. This is a proactive role where you will own how we interpret data, allowing you to provide valuable insight into the development and implementation of product, customer and channel strategies for our sales, retention, and acquisition goals.',
skills: [{Skill value}],
salary: [{Salary value}],
education: newEducations,
popularity: 0,
reccomendations: [{Recommendation value}]
});
After this saved.
Does it that you want?
This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
Closed 3 years ago.
I looked at other questions and I feel mine was different enough to ask.
I am sending a (potentially) large amount of information back to my backend, here is an example data set:
[ { orders: [Array],
_id: '5c919285bde87b1fc32b7553',
name: 'Test',
date: '2019-03-19',
customerName: 'Amego',
customerPhone: '9991112222',
customerStreet: 'Lost Ave',
customerCity: 'WestZone',
driver: 'CoolCat',
driverReq: false, // this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '38.48',
taxTotal: '5.00',
finalTotal: '43.48',
__v: 0 },
{ orders: [Array],
_id: '5c919233bde87b1fc32b7552',
name: 'Test',
date: '2019-03-19',
customerName: 'Foo',
customerPhone: '9991112222',
customerStreet: 'Found Ave',
customerCity: 'EastZone',
driver: 'ChillDog',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '9.99',
taxTotal: '1.30',
finalTotal: '11.29',
__v: 0 },
{ orders: [Array],
_id: '5c91903b6e0b7f1f4afc5c43',
name: 'Test',
date: '2019-03-19',
customerName: 'Boobert',
customerPhone: '9991112222',
customerStreet: 'Narnia',
customerCity: 'SouthSzone',
driver: 'SadSeal',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '41.78',
taxTotal: '5.43',
finalTotal: '47.21',
__v: 0 } ] }
My front end can find all the orders that include isPrinted:false, I then allow the end user to 'print' all the orders that are prepared, in which, I need to change isPrinted into true, that way when I pull up a next batch I won't have reprints.
I was looking at db.test.updateMany({foo: "bar"}, {$set: {isPrinted: true}}), and I currently allow each order to set a new driver, which I update by:
Order.update({
_id: mongoose.Types.ObjectId(req.body.id)
},
{
$set: {
driver:req.body.driver, driverReq:false
}
which is pretty straight forward, as only 1 order comes back at a time.
I have considered my front end doing a foreach and posting each order individually, then updating the isPrinted individually but that seems quite inefficient. Is there a elegant solutions within mongo for this?
I'm not sure how I would user updateMany considering each _id is unique, unless I grab all the order's who are both driverReq:false and isPrinted:false (because that is the case where they are ready to print.
I found a solution, that was in fact using UpdateMany.
Order.updateMany({
isPrinted: false, driverReq:false
},
{
$set: {
isPrinted: true
}
consider there this special case where both are false when it needs to be changed too true. But I do wonder if there is a way to iterate over multiple document id's with ease.
Not quite sure if that title was the best I could do.
I'm a pretty new to js and keep running into problems ... I hope some of you have the time to give me a pointer or two on this scenario.
I have several objects that looks pretty much like this - except from the fact that there are 28 instances of every "room" type. I need to split this object into multiple objects - one for each "room" type. In some of my objects there are only one room type - whilst in others there are 3 or 4.
[ { id: 1
created: 2018-12-29T13:18:05.788Z,
room: 'Double Room'
type: 'Standard'
price: 500
},
{ id: 29
created: 2018-12-29T13:18:05.788Z,
room: 'Twin Room'
type: 'Standard'
price: 500
},
{ id: 58
created: 2018-12-29T13:18:05.788Z,
room: 'Family Room'
type: 'Standard'
price: 900
},
]
Oh, and it's important that the instances don't "loose" their order in the array - since it's date related and need to be presentet in an ascending order. And vanilla js only.
Is array.map() the function I'm looking for to solve this problem? Is it posible to do this without iteration?
My final goal is to create some kind of generic function that can sort this out for all my objects.
And guys: happy hollidays!
You could take an object as hash table for the wanted groups. Then iterate the objects and assign the object to the group. If the group does not exist, create a new group with an array.
function groupBy(array, key) {
var groups = Object.create(null);
array.forEach(o => (groups[o[key]] = groups[o[key]] || []).push(o));
return groups;
}
var data = [{ id: 1, created: '2018-12-29T13:18:05.788Z', room: 'Double Room', type: 'Standard', price: 500 }, { id: 29, created: '2018-12-29T13:18:05.788Z', room: 'Twin Room', type: 'Standard', price: 500 }, { id: 58, created: '2018-12-29T13:18:05.788Z', room: 'Family Room', type: 'Standard', price: 900 }],
groupedByRoom = groupBy(data, 'room');
console.log(groupedByRoom);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm still trying to find my way with AngularJS. I have a JavaScript code that uses URL to return JSON data as an array. I need help with populating the same data in select using ng-options.
data to populate on the select
This isn't how you ask for help, but nevermind. Given a JSON object like this
var JsonArray = [{
id: 1,
name: 'Jane',
address: 'Jane\'s house'
}, {
id: 2,
name: 'Jill',
address: 'Jill\'s house'
}, {
id: 3,
name: 'John',
address: 'John\'s house'
}, {
id: 4,
name: 'Jack',
address: 'Jack\'s house'
}];
When you want to use ng-select with ng-options, you need to specify 3 required fields :
your table
the name that every object will take (like a for ... each loop)
The property you want to see in your options
You also can specify a track by property to give your options a given value.
<select ng-model="mySelect" ng-options="object.name for object in JsonArray track by object.id"></select>
Now, use the last piece of code, and inspect it in a brwoser. You will understand everything.
For reference :
<select ng-model="mySelect" ng-options="[object].[chosenProperty] for [object] in [yourArray] track by [object].[property]"></select>
I have a complex JSON response that is iterated over using ng-repeat. Only a relatively small subset of the attributes within the result set are displayed on the screen, so filtering of the results should be restricted to values the user can actually see, otherwise the filtering behavior would be confusing to the end-user.
Since one of the attributes I wish to filter on is a deeply nested array, a custom filter was needed since the built-in AngularJS filterFilter does not iterate over the array elements to the best of my knowledge.
I was able to get this working some time back in AngularJS v1.2.28, but unfortunately it appears to break during a migration to v1.4.3. I have not spent time to isolate where in the release cadence this functionality broke however.
I have not found any helpful information in the migration guides that would indicate what has changed. All I know is that the actual/expected parameters to the filter receive different values in the latest major version of AngularJS, which leads to the failure.
ng-repeat filter expression:
<li ng-repeat="user in users | list_filter:{establishment: {id: filterText, names: [{name: filterText}], locations: [{streetAddress1: filterText, streetAddress2: filterText, city: filterText, stateProvince: filterText, postalCode: filterText}]}}">
Example data structure of a single element:
data = [{
id: 234567,
name: 'John Doe',
establishment: {
id: 067915959,
locations: [{
id: '134B030365F5204EE05400212856E994',
type: 'postal',
streetAddress1: 'P O BOX 900',
city: 'Grover',
stateProvince: 'CA',
postalCode: '902340900',
isoCountryCode: 'US',
region: 'MONROE'
}, {
id: '999B030365F4204EE05400212856E991',
type: 'postal',
streetAddress1: '2590 Atlantic Ave',
city: 'Fredricks',
stateProvince: 'VA',
postalCode: '45487',
isoCountryCode: 'US',
region: 'MONROE'
}],
names: [{
name: 'Grover Central School Dst',
type: 'PRIMARY'
}, {
name: 'Grover Central School Dst',
type: 'MARKETING'
}, {
name: 'Grover CENTRAL SCHOOL DISTRICT',
type: 'LEGAL'
}]
}
}];
Supporting Plunker Examples:
Plunker for version 1.2.28:
http://plnkr.co/edit/KD1MmNMBEhO7X2v9yK4S?p=info
Plunker for version
1.4.3: http://plnkr.co/edit/OmPOOwRWCHuPutUtWOcC?p=info
Edit:
The issue appears to be directly related to the changes introduced in v1.3.6.
It appears the issue is related to the fact that an implicit AND condition is now being applied but was previously an implicit OR, which is what is desired in my case. You can import the old version as a separate filter, if the old behavior is desired.