NodeJS- ExpressJS mongoose API POST Request with foreign key - json

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"
});
});
});

Related

How to map an object from JSON file to another object?

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.

Converting Array to bulk Create in nodejs with Sequelize

This is my req.body json data from angularjs controller:
{
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
}
i want to get gsm values from req.body
I want to make the above structure into this type:
[{phoneno:123457801;sender:'ifelse';message:'Hello Test'},{phoneno:123450987;sender:ifelse;message:'Hello Test'}]
then only i am able to insert in mysql.
I think it will helpful to you!...
var body={
phoneno: [
{ id: 1, gsm: '123457801', firstName: 'Mohamed', lastName: 'Sameer'},
{ id: 2, gsm: '123450987', firstName: 'Hameed', lastName: 'Basha' }
],
sender: 'ifelse',
message: 'Hello Test'
};
var new_req_body=[];
for(var i=0;i<body.phoneno.length;i++){
var new_arr={
sender:body.sender,
message:body.message,
phoneno:body.phoneno[i].gsm
};
new_req_body.push(new_arr);
}
console.log(new_req_body);

Kendo UI Chart - Visualize count of returned JSON fields

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

Json error - Cannot access child value on newtonsoft.json.linq.jproperty.

I have the following Json -
Property {
id: 122334,
source:
[ id : 123,
address:
{
city: "little rock",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 222,
name: "The wall",
count: 2
}, ]
[ {id: 8889,
address:
{
city: "milka",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 555,
name: "The watt",
count: 3
},
},
]
}
I am parsing it the following way -
string data = client.DownloadString(URL);
JToken token = JObject.Parse(data);
if (!string.IsNullOrEmpty(Convert.ToString(token["property"].Children())))
{
token["property"].Children().ToList().ForEach(child =>
{
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
if (GetID == id)
{
//move rest of the code here
}
else
{
}
});
}
But I get the execption - cannot access child value on newtonsoft.json.linq.jproperty.
at the line -
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
What am I doing wrong?
enter code here

Ember.Data JSON not being pushed into store

I am having trouble getting my API json results to be pushed into the Ember Data object model array. I was previously using getJSON on my route however I now need to be able to filter the data on multiple properties and Ember Data provides built in methods for that...if I could get it work that is. I'm pretty new to this so I am probably missing something terribly obvious. Please let me know if I am missing any code to assist. When I look at the promises, it shows them fulfilled when pulling the data from the API but then it rejects when trying to query the local data store for records (shows null) which I believe means my data isn't getting added to the store in the first place. I would provide a JSBin but our api uses CORS and I can't get the JSbin origin to authenticate.
On the route I have tried the following. Both throw different errors:
return this.store.find('restaurant');
//returns error: Error while processing route: casualdining
//Array.prototype.map: 'this' is null or undefined.
return DineSection.Restaurant.find();
//Error while processing route: casualdining
//Object doesn't support property or method 'find'
The Application Code:
DineSection = Ember.Application.create({
rootElement: "#dinesection-app"
});
DineSection.Router.map(function () {
this.resource("casualdining");
this.resource("restaurant", { path: "/:id" });
});
DineSection.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://api.lakecountyfl.gov',
namespace: 'api/TourismListings',
pathForType: function (type) {
return "GetRestaurants";
}
});
DineSection.ApplicationStore = DS.Store.extend({
adapter: 'DineSection.ApplicationAdapter'
});
//SERIALIZE OUR JSON DATA FROM THE API into something ember data can use
DineSection.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function (type, payload) {
return { restaurant: payload }
}
});
DineSection.Restaurant = DS.Model.extend({
name: DS.attr('string'),
address: DS.attr('string'),
city: DS.attr('string'),
zip: DS.attr('string'),
phone: DS.attr('string'),
website: DS.attr('string'),
facebook: DS.attr('string'),
flickr: DS.attr('string'),
hasphoto: DS.attr('boolean', {defaultValue: false}),
outdoordining: DS.attr('boolean', { defaultValue: false }),
breakfastprice: DS.attr('string'),
lunchprice: DS.attr('string'),
dinnerprice: DS.attr('string'),
description: DS.attr('string'),
primarycategoryname: DS.attr('string'),
primarycategoryslug: DS.attr('string'),
primarysubcategoryname: DS.attr('string'),
primarysubcategoryslug: DS.attr('string'),
foodtype: DS.attr('string'),
foodtypeid: DS.attr('number'),
ranking: DS.attr('number'),
region1: DS.attr('boolean', { defaultValue: false }),
region2: DS.attr('boolean', { defaultValue: false }),
region3: DS.attr('boolean', { defaultValue: false }),
region4: DS.attr('boolean', { defaultValue: false })
});
DineSection.CasualdiningRoute = Ember.Route.extend({
model: function () {
//return Ember.$.getJSON("https://devapi.lakecountyfl.gov/api/TourismListings/GetRestaurants");
return this.store.find('restaurant');
//return DineSection.Restaurant.find();
}
});
My JSON response looks like this (abbreviated to two records for simplicity):
[{
"$id": "1",
"id": 1212,
"name": "Al's Landing",
"address": "111 W. Ruby St.",
"city": "Tavares",
"zip": "32778",
"phone": "352-555-8585",
"website": "http://www.alslanding.com",
"facebook": "https://www.facebook.com/pages/ALS-landing/110275062350544",
"flickr": null,
"hasphoto": true,
"outdoordining": true,
"breakfastprice": "N/A",
"lunchprice": "$10-$20",
"dinnerprice": "$10-$20",
"description": "A casual dining atmosphere with an indoor/ outdoor bar and plenty of outdoor lakefront seating.",
"primarycategoryname": "Dining",
"primarycategoryslug": "dining",
"primarysubcategoryname": "Casual Dining",
"primarysubcategoryslug": "casualdining",
"foodtype": "American",
"foodtypeid": 13,
"ranking": 3,
"region1": false,
"region2": false,
"region3": true,
"region4": false
},
{
"$id": "2",
"id": 1026,
"name": "#1 Wok",
"address": "1080 E. Highway 50",
"city": "Clermont",
"zip": "34711",
"phone": "352-555-2346",
"website": "",
"facebook": "",
"flickr": "",
"hasphoto": false,
"outdoordining": false,
"breakfastprice": "N/A",
"lunchprice": "Less than $10",
"dinnerprice": "Less than $10",
"description": "",
"primarycategoryname": "Dining",
"primarycategoryslug": "dining",
"primarysubcategoryname": "Casual Dining",
"primarysubcategoryslug": "casualdining",
"foodtype": "Asian",
"foodtypeid": 1,
"ranking": 1,
"region1": false,
"region2": false,
"region3": false,
"region4": true
}
]
I think you need a 'root' key in your JSON like follows:
[ restaurants: {