Related
Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.
I'm trying to create an REST API in JSON. I have 2 models, an business and an address. An Address is part of a business
When I try to create a POST request with the following JSON
{
"name" :"GRIT",
"adress":
{
"street" : "test",
"number": "5",
"city":"leuven",
"postalcode":"2900",
"country":"BEL"
}
}
I get the following error
{
"error": {
"errors": {
"adress": {
"message": "Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectID",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress",
"reason": {
"message": "Cast to ObjectId failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "CastError",
"stringValue": "\"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\"",
"kind": "ObjectId",
"value": {
"id": "5ad8b5e4ac4b1a443877bfc2",
"street": "test",
"number": "5",
"city": "leuven",
"postalcode": "2900",
"country": "BEL"
},
"path": "adress"
}
}
},
"_message": "Business validation failed",
"message": "Business validation failed: adress: Cast to ObjectID failed for value \"{ id: 5ad8b5e4ac4b1a443877bfc2,\n street: 'test',\n number: '5',\n city: 'leuven',\n postalcode: '2900',\n country: 'BEL' }\" at path \"adress\"",
"name": "ValidationError"
}
}
These are my mongoose models
const mongoose = require('mongoose');
const businessSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name:{
type: String,
required: true,
},
adress:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Adress',
required:true
}
});
module.exports = mongoose.model('Business', businessSchema);
const mongoose = require('mongoose');
const adressSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
street:{
type: String,
required: true
},
number:{
type: int,
required: true
},
city:{
type: String,
required: true
},
postalCode:{
type: String,
required: true
},
country:{
type: String,
required: true
}
});
module.exports = mongoose.model('Adress', adressSchema);
The following is my Post request
//POST -> Register a business
router.post('/',function(req,res){
const business = new Business({
id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress:{
id:new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country:req.body.adress.country
}
});
business
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Business created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
module.exports = router;
What did I do wrong? Does the adress doesn't save or do I link the two models wrong with eachother
I am using MongoDB as a Datbase
Take a look at the mongoose docs.
You are trying to set a ObjectId property with an Adress object. What you have to do is first save your adress object, and then reference it inside your business object.
PS: You should name your ids as _id since thats the convention used in MongoDB.
It would look something like this:
let adress = new Adress({
_id: new mongoose.Types.ObjectId(),
street: req.body.adress.street,
number: req.body.adress.number,
city: req.body.adress.city,
postalcode: req.body.adress.postalcode,
country: req.body.adress.country
});
adress
.save()
.then(() => {
let business = new Business({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
adress: adress._id
});
business
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: "Business created"
});
});
});
Im using 'json-csv' library to create a csv from a users arrays with nested objects and arrays.
var users = [
{
subscriptions: [
{
package : {
name: 'Grammar'
},
state: 'EXPIRED',
timerange: {
period : 5550
},
transaction:{
amount: 10000
}
},
{
package : {
name: 'GK'
},
state: 'ACTIVE',
timerange: {
period : 30
},
transaction:{
amount: 10340
}
},
],
account:{
balance: 200
},
name: "Johhy Moe",
email: null,
user_id: "123456789",
username: null,
user_type: "facebook",
id: 3,
createdAt: "2016-07-11T08:02:40.000Z",
updatedAt: "2016-07-11T08:02:40.000Z",
},
{
subscriptions: [
{
package : {
name: 'GK'
},
state: 'EXPIRED',
timerange: {
period : 42
},
transaction:{
amount: 5252
}
},
{
package : {
name: 'MATH'
},
state: 'ACTIVE',
timerange: {
period : 25
},
transaction:{
amount: 200
}
}
],
account:{
balance: 1500
},
name: "John Doe",
email: null,
user_id: "123456789",
username: null,
user_type: "facebook",
id: 7,
createdAt: "2016-07-29T06:44:18.000Z",
updatedAt: "2016-07-29T06:44:18.000Z"
},
]
Now i want the generated csv to be like this
USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD
3,Johhy Moe,123456789,200,Grammar,10000,EXPIRED,5550
3,Johhy Moe,123456789,200,GK,10340,ACTIVE,30
7,John Doe,123456789,1500,GK,5252,EXPIRED,30
7,John Doe,123456789,1500,MATH,200,ACTIVE,25
As you see if there are two objects inside subscription array for each user, i want to repeat that user again but with different subscription data.
I've thought of using the library because my users array can go up to thousands of users with hundreds of subscription.
And i'm at a loss to what i should do.
my Code:
var options= {
fields : [
{
name : 'id',
label : 'USERID'
},
{
name : 'name',
label : 'Name'
},
{
name : 'user_id',
label : 'FBID'
},
{
name : 'account.balance',
label : 'ACCOUNT'
},
{
name: '',
label: 'Subscription'
}
]
}
var source = es.readArray(users)
source
.pipe(jsoncsv.csv(options))
.pipe(res)
I dont want to use a library also. So if someone could provide me with a resource to make my own csv file with strings and also using streams , that would be great. Thanks!!
This will solve your problem. Now you just have to change console.log to fs and write to your file.
var json2csv = function (json, listKeys) {
var str = "";
var prefix = "";
for (var i = 0; i < listKeys.length; i++) {
str += prefix + json[listKeys[i]];
prefix = ",";
}
return str;
};
var async = require('async');
var csvData = ['USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD'];
async.each(users, function (user, callback) {
var csvRow1 = {
USERID: user.id,
NAME: user.name,
FBID: user.user_id,
ACCOUNT: user.account.balance
};
async.each(user.subscriptions, function (subscription, callback) {
var csvRow2 = JSON.parse(JSON.stringify(csvRow1));
csvRow2.SUBSCRIPTION = subscription.package.name;
csvRow2.PRICE = subscription.transaction.amount;
csvRow2.STATE = subscription.state;
csvRow2.TIMEPERIOD = subscription.timerange.period;
csvData.push(json2csv(csvRow2, ['USERID', 'NAME', 'FBID', 'ACCOUNT', 'SUBSCRIPTION', 'PRICE', 'STATE', 'TIMEPERIOD']));
callback(null);
}, function (err) {
callback(err);
});
}, function (err) {
if (err) {
// return err;
} else {
// return csvData;
}
});
I want to display the counts of specific retrieved fields in my pie/donut chart.
I'm retrieving data via REST and the result is in json format. The source is a list repeating values:
Example: In the following list, I'd like to get a present the number (count) of completed responses; perhaps in a second chart present the breakdown of responses by location.
var userResponse = [
{ User: "Bob Smith", Status: "Completed", Location: "USA" },
{ User: "Jim Smith", Status: "In-Progress", Location: "USA" },
{ User: "Jane Smith", Status: "Completed", Location: "USA" },
{ User: "Bill Smith", Status: "Completed", Location: "Japan" },
{ User: "Kate Smith", Status: "In-Progress", Location: "Japan" },
{ User: "Sam Smith", Status: "In-Progress", Location: "USA" },
]
My Initialization currently looks like this:
$('#targetChart').kendoChart({
dataSource: {
data: data.d.results,
group: {
field: "Location",
},
},
seriesDefaults: {
type: "donut",
},
series: [{
field: 'Id',
categoryField: 'Location',
}],
});
You can easily transform the data. Read it into a DataSource object grouping by location and filtering for completed only. Then fetch the data and create an array of the counts for each location:
var pieData = [];
var respDS = new kendo.data.DataSource({
data: userResponse,
group: {
field: "Location",
},
filter: {
field: "Status",
operator: "eq",
value: "Completed" },
});
respDS.fetch(function(){
var view = respDS.view();
for (var i=0; i<view.length; i++){
var item = {};
item.Location = view[i].value;
item.Count = view[i].items.length;
pieData.push(item);
}
});
You end up with:
[
{Location: "Japan", Count: 1},
{Location: "USA", Count: 2},
]
This can then be bound to a pie/donut.
DEMO
I'm trying to access amount. I can see datas :
Schema :
var schema = mongoose.Schema({
investors : {
id : String,
amount : Number,
user_id : String,
inv_profit : Number
}
});
Command
invs2.findOne({}, function(err, data){
console.log(data)
})
Output :
{ _id: 54159a1c291df572283fa4de,
investors:
[ { inv_profit: 0,
user_id: 'userID',
amount: 1.2,
id: '1410701852660' },
{ inv_profit: 0,
user_id: 'userID',
amount: 1.2,
id: '1410701858752' } ] }
invs2.findOne({}, function(err, data){
console.log(data.investors)
})
Output:
[ { id: '1410701852660',
amount: 1.2,
user_id: 'userID',
inv_profit: 0 },
{ id: '1410701858752',
amount: 1.2,
user_id: 'userID',
inv_profit: 0 } ]
But when I trying to access data.investors[0].amount I'm getting undefined?
Even data.investors.length is returning undefined.
There is only one entry in invs2 collection.
investors should be defined as an array in your schema if it's an array of sub-docs:
var schema = mongoose.Schema({
investors : [{
id : String,
amount : Number,
user_id : String,
inv_profit : Number
}]
});