Firebase: How to retrieve data from two tables using id - ionic-framework

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

Related

Read nested data from firebase realtime database in flutter

If you see the screenshot of my database, the data is stored in a nested way (cartProduct is a key which has a value of an entire Json file with keys: "id", "price" etc.). In my code, I create a map of each record in the "Orders" table in order to retrieve key values of any key that I specify. This is done by specifying the key name in the databaseMapper variable.
I am trying to read the value of each "id" and store it in a list called "testerList". I am able to store each orderNum, totalAmount or any of those key values that I specify in the databaseMapper. However, if I specify ["id"] it does not work.
I did some research and saw that the only way to reference nested items in a map is by using the logic: databaseMapper["cartProduct"]["id"] like I did below, but I keep getting an error (see last screenshot).
Any help would be appreciated!
Future _readItemIDsTest() async {
//Stores each record in the table as a map
var snapshot = await _dbRef.child("Orders").get();
snapshot.children.forEach((childSnapshot) {
var databaseMapper = childSnapshot.value as Map;
testerList.addAll([databaseMapper["cartProduct"]["id"]]);
});
print(testerList);
}
Nvm, I figured it out. The code below solved my issue.
Future _readItemIDsTest() async {
//Stores each record in the table as a map
//Adds the itemName value of each item from the map
var snapshot = await _dbRef.child("Orders").get();
snapshot.children.forEach((childSnapshot) {
databaseMapper = childSnapshot.value as Map;
var cartProductList = databaseMapper["cartProduct"];
(cartProductList as List).forEach((cartProductElement) {
testerList.addAll([cartProductElement["id"]]);
});
});
print(testerList);
}

Remove Filter from table in SAP UI5

I want to display all table records when is there is filter field is empty or blank. Whenever there is value in USER Field, data is getting filtered based on value. Now I want to display all records if USER field is blank or empty.
Could you please help.
Below is the code
onSettingsSaveBtn: function (oEvent) {
var oModel = this._oSettingsDialog.getModel("SettingsContext"),
oData = oModel.getData(),
user = oData.StoreID;
var aTableSearchState = [];
aTableSearchState = [new Filter("DeliveryStatus", "EQ", user)];
var oBinding = this._oTable1.getBinding("items");
this._oSettingsDialog.close();
if (user === "") {
}
else {
oBinding.filter(aTableSearchState,"Application");
}
}

MongoDB : How to find multiple documents and update at the same time?

I have mongo DB and I am using C#.Net to interact with mongo db. C# API has methods for finding a single document and updating it at the same time. For example FindOneAndUpdateAsync.
However I couldn't find any method to find multiple documents and update them at the same time asynchronously.
The code below finding and processing each document asynchronously. How do I also update that document at the same time?
public async Task<IList<IDictionary<string, string>>> DoWork()
{
var collection = _mongoDatabase.GetCollection<BsonDocument>("units");
var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Ne<string>("status", "INIT") &
(filterBuilder.Exists("isDone", false) |
filterBuilder.Eq<bool>("isDone", false));
// I want to pass this update filter to update the document. But not sure how
var update = Builders<BsonDocument>.Update
.CurrentDate("startTime");
var sort = Builders<BsonDocument>.Sort.Ascending("startTime");
var projection = Builders<BsonDocument>.Projection
.Include("_id")
.Include("fileName"); // for bravity i have removed other projection elements
var output = new List<IDictionary<string, string>>();
// How do i pass update filter and update the document at the same time??
await collection
.Find(filter)
.Sort(sort)
.Project(projection)
.ForEachAsync((unit) =>
{
var dictionary = new Dictionary<string, string>();
Recurse(unit, dictionary);
output.Add(dictionary);
});
return output.Count > 0 ? output : null;
}
That doesn't exist in the mongo .Net api see here.
Just use a combination of Find and UpdateManyAsync.

How to use fetch with with sending the Id

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();

Entity framework ToList() isn't working

I have some code like this:
var db = new MYContext();
var invoice = new Invoice { InvoiceId = 7 };
db.Set<Invoice>().Add(invoice);
var invoiceFound = db.Set<Invoice>().Find(7);
var invoices = db.Set<Invoice>().ToList();
invoiceFound gets populated with the invoice.
The problem is invoices is returning an empty list.
Could someone please explain this to me?
If I remember correctly, calling ToList() makes a call to the database and returns the result set. Since you have not saved your changes (add of the invoice) before calling ToList(), the Invoice you added will not be in the result set. There is a Local property on DbSet that returns your in memory collection of Invoices. This collection will contain the Invoice you added even if you don't SaveChanges().
Please try this one:
var db = new MYContext();
var invoice = new Invoice { ID = 7 };
db.AddToInvoice(invoice);
db.SaveChanges();
var qry = from item in db.Country select item;
IList<Invoice> list = qry.ToList<Invoice>();