I am developing a Node.js/Backbone.js SPA and moving some of my data from JSON files to Mongo. I have set up an api with Mongoose and my data is posting to the server. However, when I try to fetch the data from Mongo it only returns the last item in my collection.
The only change in my Backbone.js code is the url I define in the Backbone Collection.
Old Collection that fetched all JSON data without a problem:
var SupplyCategoriesCollection = Backbone.Collection.extend({
model: SupplyCategory,
url: '/supplies',
});
New Collection only fetches last item in Mongo database
var SupplyCategoriesCollection = Backbone.Collection.extend({
model: SupplyCategory,
url: '/api/products',
});
When I navigate to http://localhost:3000/api/products I get the exact same data as when I navigate to http://localhost:3000/supplies.
The answer is that I had not changed the default idAttribute in my Backbone collection and model:
e.g.:
var SupplyCategoriesCollection = Backbone.Collection.extend({
model: SupplyCategory,
url: '/api/products/',
"idAttribute: "_id",
});
Related
My server response is having two objects (picture):
How can i put just secound object members (models) in my Backbone Collection. I am using collection.fetch to get data from server. Can I somehowe addapt my server response.
You can do this by overriding the parse method of your collection:
var coll = Backbone.Collection.extend({
parse: function(data){
return data.statuses;
}
});
Your Collection will contain what you return from your parse function, in this case you reduce it to the statuses array from your server response.
use parse()
see:
http://backbonejs.org/#Collection-parse
in your collection:
yourCollection = Backbone.Collection.extend({
//other collection stuff.
parse: function(response) {
//save the search metadata in case you need it later
this.search_meatadata = response["search_metadata"];
// return the array of objects.
return response["statuses"];
}
});
I'm doing an application with Backbone.js and Require.js. I have an "Opportunities" Backbone collection and I needed to modify the fetch method because the data from the server comes inside a "results" object.
I did the trick by doing something I found in this question, at this point all looks good.
The problem is that I noticed that the fetch method is asking the server for the data TWO TIMES and not ONE as expected.
I am testing and now I found that if I remove this code: return Backbone.Collection.prototype.fetch.call(this, options); Backbone asks the url for the data only one time, obviously this code is causing the problem but I don't know the reason.
This is my Backbone collection
define([
'backbone',
'models/Opportunity'
], function(Backbone, Opportunity){
var Opportunities = Backbone.Collection.extend({
url: "/api/v1/opps/",
model: Opportunity,
// Need to have custom fetch because json data is coming inside a
// "results" array inside the JSON.
fetch : function(options) {
// store reference for this collection
var collection = this;
$.ajax({
type : 'GET',
url : this.url,
dataType : 'json',
success : function(data) {
// set collection main data
collection.reset(data.results);
}
});
// For some reason this is causing a double request
// to the server
return Backbone.Collection.prototype.fetch.call(this, options);
}
});
return Opportunities;
});
Someone knows the reason because this error is happening?
It's fetching it twice because you're using jQuery to fetch it directly, the calling the models own fetch method which will call an AJAX request as well.
If you want to return data.results back to your collection (and subsequently models), you can use the parse method, like:
var Opportunities = Backbone.Collection.extend({
url: "/api/v1/opps/",
model: Opportunity,
parse: function(data){
return data.results;
}
});
I have a Backbone Collection like so:
var ThreadCollection = Backbone.Collection.extend({
url: '/api/rest/thread/getList'
});
var myCollection = new ThreadCollection();
And then I'm fetching it from the server using the data object to append the query parameters (so in this case it comes out '/api/rest/thread/getList?userId=487343')
myCollection.fetch({
data: {
userId: 487343
}
})
There are other parameters that I may want to use instead of userId (groupId, orgId, etc) but I'd ideally define the data parameters upon initialization and from then on be able to run fetch() without specifying. Something like this:
var myCollection = new ThreadCollection({
data: {
userId: 487343
}
});
myCollection.fetch()
but it doesn't work. Does anyone know if there's a way to do this? Thanks!
One way is to define a custom fetch method on your collection which calls the super fetch method with some overridable defaults:
var ThreadCollection = Backbone.Collection.extend({
url: '/api/rest/thread/getList',
fetch: function(options) {
return Backbone.Collection.prototype.fetch.call(this, _.extend({
data: {
userId: 48743
}
}, options));
}
});
var myCollection = new ThreadCollection();
myCollection.fetch();
I am trying to retrieve my models from the local storage in a collection. I enter into "success" but sometimes my collection is still empty. I thought "success" meant the collection was well fetched.
var self = this;
window.rooms= new Rooms();
window.rooms.localStorage = new Backbone.LocalStorage("rooms-backbone");
window.rooms.fetch({
success: function(model, response, options) {
rooms.each(function(room){
this.template = _.template(tpl.get('RoomView'));
$(self.el).append(this.template(room.toJSON()));
console.log(rooms.toJSON());
console.log(model);
console.log(response);
console.log(options);
});
}
});
How can i populate my UI once i am sure the collection is well filled ?
Thx in advance
Hello i have just dived into backbone.
What i am trying to do is make a collection of low_resolution photos from the instagram api feed.
I have model for user that stores all the instagram info like access_token and,
App.Models.Ig_photo({});
And a collection ,
App.Collections.Ig_photos({function() {
model: App.Models.Ig_photo,
url: "https://api.instagram.com/v1/users/self/feed?access_token=",
sync:function (method, model, options) {
options.timeout = 10000; // required, or the application won't pick up on 404 responses
options.dataType = "jsonp";
return Backbone.sync(method, model, options);
},
parse: function( response ) {
return response.data
}
}});
Now i have some issues here, that my collection doesn't get populated when i do fetch and secondly what i wanted was the accesstoken is saved in my another model called user so how do i access it here?
Also it would be great if someone suggests the approach im taking is correct or not. ?
You could add the API key to the collection model:
App.Collections.Ig_photos.access_token = OtherModel.get("access_token");
And use a function for the collection URL:
url: function() {
return "https://api.instagram.com/v1/users/self/feed?access_token=" + this.access_token
},