How to use fetch with with sending the Id - rest

Hi I have the next model in backboneJS:
var Type = Backbone.Model.extend({
url : "/api/SomeRoute"
});
var model = new Type({id:"MyAlias"});
model.fetch();
On the rest part In SomeRoute I have 2 actions which returns my Model. First which recieves the Id and returns the Model by Id and second without parameters which return the collection. But when I call fetch() in JS, it doesn't send the Id in the request. What I'm doing wrong?

If there is an id attribute specified in a model. Then the fetch request will be like /api/SomeROute/id
Instead of url give urlRoot. If urlRoot is specified then the models id will be appended.
var Type = Backbone.Model.extend({
urlRoot : "/api/SomeRoute"
});

Rewrite your url to next:
var type = Backbone.Model.extend({
url: function(){
return "/api/SomeRoute/" + this.get("id");
}
});
var model = new Type({id: "SomeId"});
model.fetch();

Related

Firestore: set post id

How can I set id of post that I'm adding? I thought that getItemNextKey() returns id that will be assigned for the post, but it's not.
AddItem(data, downloadURLs) {
data.id= this.getItemNextKey(); // Persist a document id
data.upload = downloadURLs;
// console.log('this.uploadService.downloadURLs: ' + downloadURLs);
// console.log('data.upload: ' + data.upload);
this.db.collection('items').add(data);
}
I did this and it works now.
// Add a new document with a generated id
var addDoc = this.db.collection('items').add(data).then(ref => {
var updateNested = this.db.collection('items').doc(ref.id).update({
id: ref.id
});
});
As stated in the official docs
When you use set() to create a document, you must specify an ID for
the document to create. For example:
db.collection("cities").doc("new-city-id").set(data);
If you dont want to set an ID yourself you can use add
But sometimes there isn't a meaningful ID for the document, and it's
more convenient to let Cloud Firestore auto-generate an ID for you.
You can do this by calling add():

new Model() that has fields set as select:false are not available

This is my Schema:
var userScheme = mongoose.Schema({
aField:String,
info: {
type:{
local: {
email:String
}
},
select:false
}
});
When I try to create a new user this works fine:
var newUser = new User()
newUser.aField="Something"
newUser.save()
But when I try to access the field that has select:false, I can't access the data. so this doesn't work:
var newUser = new User()
newUser.aField="something"
newUser.info.local.email="email#domain.com"
newUser.save()
The error I get is:
TypeError: Cannot read property 'local' of undefined
My guess is that the new Model is returned without the info field becuase it is set to select:false.
How can I make the new Model() return all the fields including those set to 'select:false'?
Thanks!
Turns out the select:false had nothing to do with it.
The culprit was the fact that info has no values by default and there for was not included in the model at all.
The solution was to create a new schema just for info, and to include it in the user schema like this:
var userScheme = mongoose.Schema({
aField:String,
info: {
type:infoSchema,
default:infoSchema, //Without this, the new document will still not include an 'info' document,
select:false
}
});
Hope this helps anyone. This was just 3 hours of my life.

Firebase: How to retrieve data from two tables using id

I come from an SQL background and recently started using Firebase for building an ionic shopping cart. This is the database schema:
To retrieve a user's cart, i used the following
var user_id="user1"; // Temporary initialised
var refCart = new Firebase("https://testing.firebaseio.com/cart");
var cart=$firebase(fireBaseData.refCart().child(user_id)).$asArray();
This gives the result:
item1 1
item2 2
item3 5
So tried using foreach()
var refMenu = new Firebase("https://testing.firebaseio.com/menu");
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
//var data= refMenu.child(item_id).val();
// val is not a function
//var data= refMenu.child(item_id).exportval();
// exportval is not a function
//var data = $firebase (refMenu.child(item_id)). $asArray();
// Give me an array of objects , ie attributes - OK! But what to do next ?
//console.log("DATA",data );
console.log("Item",item_id+" "+qty);
});
});
How can i use item_id to retrieve item details.
Is it the correct way of doing data retrieval from multiple tables?
Update:
Using on() function , i managed to get the item attributes.
refMenu.child(item_id).on("value", function(snapshot) {
console.log("Price",snapshot.val().price);
});
But is there any better implementation for the same.
Is there any better ways to retrieve (from the server side) specific attributes for the item.
Like in SQL
SELECT name,price, ... from menu;
NOTE: .on('event', callback) method will call your callback every time the event is fired.
If you need to retrieve data from a reference once, you should use: .once('event', callback)
NOTE2: snapshot.val() will give you a JSON object that you can assign to a variable
I would do it this way:
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
refMenu.child(item_id).once("value", function(snapshot) {
var item = snapshot.val()
console.log(item.name +' '+ item.price)
});
});
});
Hope it helps ;)

Backbonejs Model.url required?

I have an example setup to show my issue: http://jsfiddle.net/5xo4yzw2/1/
var root = "http://jsonplaceholder.typicode.com"
var Post = Backbone.Model.extend({
url: function(){
return this.get('url') || root + "/posts/" + this.get('id')
}
});
var Posts = Backbone.Collection.extend({
model: Post,
url: root + "/posts"
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
var post = new Post({id: 1});
post.fetch();
console.log("Call to collection fetch works")
This example works, that is, both of the console.logs are executed without an exception being raised by .fetch(). It was my understanding, however, from both http://backbonejs.org/#Model-url and the book I am reading, that once I specify "/posts" as the collection url, the model url should be automatically resolved to [collection.url]/[id], though that is not the case. If I do not provide the url function in the model, an exception is raises upon fetching, stating the th url parameter must be provided.
Have i misunderstood something?
You haven't added your post model to your collection, in order for a model to use the collections URL it must be part of that collection.
For example
var post = new Post({id: 1});
posts.add(post);
post.fetch();
console.log("Call to collection fetch works")
Updated Fiddle
As #Artem Baranovskii pointed out, If you want to use a model outside a collection you should be using the urlRoot property. From the documentation
Specify a urlRoot if you're using a model outside of a collection, to
enable the default url function to generate URLs based on the model
id. "[urlRoot]/id" Normally, you won't need to define this. Note that
urlRoot may also be a function.
If you're using a model outside of the collection you could use urlRoot like the following:
var root = "http://jsonplaceholder.typicode.com"
var Posts = Backbone.Model.extend({
urlRoot: function () {
return this.get('url') || (root + "/posts/" + this.get('id'))
}
});
var posts = new Posts();
posts.fetch();
console.log("Call to collection fetch works")
When you execute fetch the model tries to get url by the several approaches here

Facebook api search in Asp.mvc 3 app

EDITED
I'm searching users in facebook using graph api in my asp.net mvc 3 application.
public void AsyncSearch(ICollection<JSonObject> result, string query, string objectType)
{
var fbClient = new FacebookClient(FacebookTokens.AccessToken);
var searchUri = string.Format("/search?q={0}&type={1}, query, objectType);
var tempResult = (JsonObject)fbClient.Get(searchUri);
var elements = (JsonArray)tempResult.Values.ToArray()[0];
elements.ForEach(element =>
{
result.Add(element);
});
var next = (JsonObject)tempResult.Values.ToList()[1];
while (next.Keys.Contains("next"))
{
tempResult = (JsonObject)fbClient.Get((string)next["next"]);
elements = (JsonArray)tempResult.Values.ToArray()[0];
elements.ForEach(element =>
{
result.Add(element);
});
next = (JsonObject)tempResult.Values.ToList()[1];
}
}
But result contains at most 600 objects(each search returns different number of objects).
I think, if i put, for example, "anna" in query parameter - result must be over 10000.
Why is that? Is there any way to retrieve all users by some keyword?
For performance concerns Facebook will paginate their results. If you look at the end of the JSON object, there should be a pageing object that has next and previous links in it. So, to get all results you will need to run multiple queries and aggregate them up on your side.