backbone collection fetch error - json

I'm trying to fetch a collection from a .json file. Here is my collection code
define(['jquery', 'underscore', 'backbone', 'vent'], function($, _, Backbone, vent) {
'use strict';
var Wine = Backbone.Model.extend({
urlRoot: "js/models/wines.json",
defaults: {
"id": null,
"name": "",
"grapes": "",
"country": "USA",
"region": "California",
"year": "",
"description": "",
"picture": ""
}
});
return Backbone.Collection.extend({
model: Wine,
url: "js/models/wines.json",
});
});
I'm fetching the collection like this:
var _wine = new wineCollection();
_wine.fetch({
success : function(data) {
console.log("ON SUCCESS");
console.log(data);
},
error: function(response) {
console.log("ON ERROR");
console.log(response);
}
});
In the console it's always showing the "ON ERROR" message:
ON ERROR
child
_byCid: Object
_byId: Object
_callbacks: Object
length: 0
models: Array[0]
__proto__: ctor
And here is one item of my wines.json file
{"id":"9","name":"BLOCK NINE","year":"2009","grapes":"Pinot Noir","country":"USA","region":"California","description":"With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.","picture":"block_nine.jpg"}
What am I doing wrong?

Have you tried inspecting the collection class in the fetch method (what is actually send over).
You might need to override the parse method in order to access an inner part of the data send over.
For instance:
Wine.Collection = Backbone.Collection.extend({
//we need to parse only the inner list
parse : function (response) {
this.cursor = response.cursor;
return response.list;
}
Where the array is an inner list: {list: [{item: one}, {item: two}]}

Related

Struggling to get data from AWS lambda JSON

I'm working on a lambda project and getting data from an API inside the function which looks like this
{ "Title": "300", "Year": "2006", "Rated": "R", "Released": "09 Mar 2007", "Runtime": "117 min", "Genre": "Action, Fantasy, War", "Director": "Zack Snyder", "Writer": "Zack Snyder (screenplay), Kurt Johnstad (screenplay), Michael B. Gordon (screenplay), Frank Miller (graphic novel), Lynn Varley (graphic novel)", "Actors": "Gerard Butler, Lena Headey, Dominic West, David Wenham", "Plot": "King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.", "Language": "English", "Country": "USA, Canada, Bulgaria", "Awards": "17 wins & 45 nominations.", "Poster": "https://m.media-amazon.com/images/M/MV5BMjc4OTc0ODgwNV5BMl5BanBnXkFtZTcwNjM1ODE0MQ##._V1_SX300.jpg", "Ratings": [ { "Source": "Internet Movie Database", "Value": "7.7/10" }, { "Source": "Rotten Tomatoes", "Value": "60%" }, { "Source": "Metacritic", "Value": "52/100" } ], "Metascore": "52", "imdbRating": "7.7", "imdbVotes": "691,774", "imdbID": "tt0416449", "Type": "movie", "DVD": "31 Jul 2007", "BoxOffice": "$210,500,000", "Production": "Warner Bros. Pictures", "Website": "http://300themovie.warnerbros.com/", "Response": "True" }
I've tried dot notation, indexing all sorts but no matter what I try, the console log just comes out with
2019-06-14T18:33:46.394Z ecc5d247-6475-464e-8dd7-bec310d98c4a INFO undefined
Has anyone else had the same issue before with lambda and lex?
Thanks
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
This currently produces a perfectly good JSON in the console but it's impossible to actually extract anything. I've tried reply.Year, reply["Year"], reply.[0].Year almost any combination I can think off.
Full Code
'use strict';
'use fetch';
// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes")
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
// --------------- Events -----------------------
function dispatch(intentRequest, callback) {
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
const sessionAttributes = intentRequest.sessionAttributes;
//const film = intentRequest.currentIntent.film;
const film = intentRequest.currentIntent.slots.film.toString();
console.log(intentRequest.currentIntent.slots.film.toString());
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
//const rating = reply.imdbRating;
console.log(reply);
callback(close(sessionAttributes, 'Fulfilled',
{'contentType': 'PlainText', 'content': `The film ${film} has a rating of `}));
}
// --------------- Main handler -----------------------
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
try {
dispatch(event,
(response) => {
callback(null, response);
});
} catch (err) {
callback(err);
}
};
I tried to reproduce the issue with that code and got the following error
Response:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'name' of undefined",
"trace": [
"TypeError: Cannot read property 'name' of undefined",
" at dispatch (/var/task/index.js:20:112)",
" at Runtime.exports.handler (/var/task/index.js:65:9)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
Line 20 of index.js for me is:
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
However when using the test event in the question event.currentIntent doesn't exist and the name property of the event object doesn't exist either.
If I remove part of the console.log statement and change it to reference the Title attribute which exists in the test event I get:
console.log(`request received for Title=${intentRequest.Title}`);
INFO request received for Title=300
Seems like the function's code is referencing attributes fine but the function's just not receiving it's expected event objects.
HTH
-James

AngularJS $scope is undefined outside of .then function

I have a a form which includes select input but the thing is ng-options is not working
Select code
<select ng-model="selectedGender" ng-options="item.value for item in genderData">
I got the data from
ReferenceService.searchCategory("GENDER").then(function (response){
$scope.genderData = response.data;
console.log($scope.genderData);
})
This is the console.log($scope.genderData)
Array(2)
0:{referenceId: 1, category: "GENDER", key: "GENDER_KEY", value: "Male", $$hashKey: "object:3"}
1:{referenceId: 2, category: "GENDER", key: "GENDER_KEY", value: "Female", $$hashKey: "object:4"}
length:2
__proto__
:
Array(0)
but I have tried hard coding the data
$scope.genderData= [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
];
and it worked! but I used ng-options="item.name for item in genderData">
btw don't mind the data I just searched it for fast use
EDIT:
I think I found the problem. Why is it undefined outside the function?
check this console
line 244 is undefined but line 242 is not?
store the response in var then out side the function assign that var to $scope. it is a callback issue.
If still it's showing same you can use localsorage to store and get the data. but this approach is not recomanded in angularjs. but if nothing happen then you can use this approcah also
That's because ReferenceService.searchCategory("GENDER") returns a promise.
A promise will wait until the data is resolved, and then move on to its success function callback. Which is the .then(function(response)).
So the code will get to the console.log on line 244 before the promise has finished, and $scope.genderData has been created and therefore is undefined
The console.log on line 242 will wait until the promise has been resolved, and calls the success callback function.
UPDATE:
Here an example how to correctly link the $scope to the factory.
Note that you must link to the object and not to its properties in your $scope.
Wrong:
$scope.gender = ReferenceService.data.genderData;
Correct:
$scope.gender = ReferenceService.data;
Example:
myApp.factory('ReferenceService',
function ()
{
var ReferenceService = {
// This is the global object. Link the $scope to this object
data: {
genderData: {}
},
searchCategory: function (type)
{
var getData = $http.get("URL", { params: { gender: type } }).then(
function (response)
{
// Store the data in the factory instead of the controller
// You can now link your controller to the ReferenceService.data
ReferenceService.data.genderData = response.data;
}
)
return getData;
}
}
return ReferenceService;
}
);
myApp.controller('MyController',
function ($scope, ReferenceService)
{
// Link $scope to data factory object
$scope.gender = ReferenceService.data;
// Now you only have to call the factory function
ReferenceService.searchCategory("GENDER");
// This will now log the correct data
console.log($scope.gender.genderData);
}
)

Populating Google Map Markers from Node Mongodb model

I need some help to populate google map markers by using data on my Mongodb with NodeJS.
This is my Model Schema (models/listing.js):
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var listingSchema = new mongoose.Schema({
category: String,
title: String,
location: String,
latitude: Number,
longitude: Number,
url: String,
type: String,
type_icon: String
},
{ collection: 'listing' }
);
// Return Model
module.exports = restful.model('Listing', listingSchema);
When I use postman to GET /api/listing, this is what I have
[{
"_id": "57092ca64f43442f0bcd6a95",
"category": "services",
"title": "Musa 24 hours Printing",
"location": "16 Bali Lane, Singapore 189852",
"latitude": 1.3007598,
"longitude": 103.8588499,
"url": "http://www.musa-group.com/24hrsinternet/printing.html",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/HwiyMCK.png"
]},
{
"_id": "57092ca64f43442f0bcd6a96",
"category": "services",
"title": "Rocket Printers SG",
"location": "146 Jalan Bukit Merah, Singapore 160146",
"latitude": 1.2778769,
"longitude": 103.8308443,
"url": "http://www.rocketprinters-sg.com/",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/XPYgZ7a.jpg"
]
}]
On my index.ejs file, the markers are currently pulled from an items.json.txt file
<script>
var _latitude = 1.36080344;
var _longitude = 103.81565094;
var jsonPath = 'assets/json/items.json.txt';
// Load JSON data and create Google Maps
$.getJSON(jsonPath)
.done(function(json) {
createHomepageGoogleMap(_latitude,_longitude,json);
})
.fail(function( jqxhr, textStatus, error ) {
console.log(error);
});
// Set if language is RTL and load Owl Carousel
$(window).load(function(){
var rtl = false; // Use RTL
initializeOwl(rtl);
});
autoComplete();
</script>
How can I change the source from 'items.json.txt' to my 'Listing' database collection? Much appreciation for any help at all!
Assuming your JSON files has the same structure as the JSON returned by /api/listing, you can simply replace the URL of your JSON file by yourserver.com:XX/api/listing, assuming the server yourserver.com is running your API on port XX.
I suspect the jQuery.getJson method is just a wrapper around jQuery.get that adds parameters to the request such as an appropriate Content-Type header.

How to get deeper in a JSON object using angularJS?

I am using AngularJs to get some information inside this JSON object, specifically the author's first and last name:
{
"bookid": "1",
"title": "Spring In Action",
"publisher": "Manning Publications Co.",
"isbn": "978-1-935182-35-1",
"owner": "Catalyst IT Services",
"publishyear": "2011",
"image": "C:/imagefolder/spring-in-action.jpg",
"description": "Totally revised for Spring 3.0, this book is a...",
"author": [
{
"authorid": "1",
"firstname": "Craig",
"lastname": "Walls",
"description": "Craig Walls has been professionally developing software for over 17 years (and longer than that for the pure geekiness of it). He is the author of Modular Java (published by Pragmatic Bookshelf) and Spring in Action and XDoclet in Action (both published by (...)"
}
],
"media": [
],
"tags": [
{
"tagid": "1",
"tagname": "Java"
},
{
"tagid": "5",
"tagname": "Spring"
}
],
"copies": [
{
"bookcopyid": "2",
"location": "Beaverton",
"status": "available"
}
]
}
The code I have right now is (which was provided by bosco2010 in this plunker (http://plnkr.co/edit/GbTfJ9)):
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
return $http.get(jsonURL).success(function (data, status) {
scope.data = data.author;
});
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope).then(function () {
$scope.nestedObj = $scope.data;
});
$scope.name = "world";
});
To get the first and last name, you'll need to reference author[0].firstname and author[0].lastname.
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL) {
return $http.get(jsonURL);
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
// The return object from $http.get is a promise. I used .then()
// to declare $scope.nestedObj after the http call has finished.
JsonSvc.read('data.json').then(function (data) {
console.log(data.data);
$scope.nestedObj = data.data.level1;
});
// ensure app is working
$scope.name = "world";
// Using nested obj within declared scope var doesn't work
// Uncomment below to break whole app
// Using nested obj in a function works but throws TypeError
// Declaring $scope.data.level1.level2 = [] first helps here
$scope.getLen = function () {
return $scope.nestedObj ? $scope.nestedObj.level2.length : ''; // return an empty string if the callback didn't happen yet
};
});
In short, it is incorrect to use both the success() function and also the then() function of the promise returned by the $htttp service.
Moreover, it is wrong to pass your scope as a parameter to your service and try to modify it there.
if you need to communicate between the service and a controller directly, you can use either $rootScope, $broadcat, or both.
I patched up your code, and now it works.
Plunk:
http://plnkr.co/edit/PlJZZn?p=preview

Backbone JS parse json attribute to a collection's model

I'm having trouble parsing a json to a model.
Here is the JSON:
[
{
"name": "Douglas Crockford",
"email": "example#gmail.com",
"_id": "50f5f5d4014e045f000002",
"__v": 0,
"items": [
{
"cena1": "Cena1",
"cena2": "Cena2",
"cena3": Cena3,
"cena4": "Cena4",
"cena5": "Cena5",
"cena6": Cena6,
"_id": "50ee3e782a3d30fe020001"
}
]
}
]
And i need a model to have the 'items' attributes like this:
cena = new Model({
cena1: "Cena1",
cena2: "Cena2",
...
});
What I've tried:
var cenaCollection = new Backbone.Collection.extend({
model: Cenas,
url: '/orders',
parse: function (response) {
return this.model = response.items;
}
});
then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|
Thanks in advance!
The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:
parse: function (response) {
return response[0].items;
}