I am trying to retrieve data from firebase realtime database in my flutter app. My data looks something like this :
This is my code :
var uid = user?.uid;
final ref = FirebaseDatabase.instance.ref('uids/$uid/sessions');
ref.onValue.listen((event) {
for (final child in event.snapshot.children) {
var dataObject = child.value.toString();
print(dataObject);
}
}, onError: (error) {});
It gives me this output :
I/flutter (16144): {2:9: Example728, 3:15: Example644, 1:45: Example, 2:11: Example184, 2:7: Example}
I/flutter (16144): {2:16: Example440, 2:26: Example124, 2:22: Example515}
I want to extract information from this jsonObject. But I have 0 idea how to do it. Do I have to make a model? If yes then how? Because the fields are actually time stamps. And I would want to access them as well as I have to display it on the screen with the date (5-11-2022 and 6-11-2022) as well.
Use this code inside the listen
//dataObject = child.value
Map dataObject = {
"5-11-2022": {
"2:9": "Example728",
"3:15": "Example644",
"1:45": "Example",
"2:11": "Example184",
"2:7": "Example",
},
"6-11-2022": {
"2:16": "Example440",
"2:26": "Example124",
"2:22": "Example515",
},
};
for (MapEntry item in dataObject.entries) {
String day = item.key.toString();
debugPrint("day: $day");
for (MapEntry item2 in dataObject[item.key].entries) {
String hour = item2.key.toString();
String value = item2.value.toString();
debugPrint("hour: $hour value: $value");
}
}
Related
I am building a list view page with multiple filters using .net core as backend and mongodb as database. I want to filter data based on some condition such that if the variable is passed as blank, it should retrieve all data, otherwise only the matching data.
In mssql this can be achieved easily by
where (#SymbolCode = '' or SymbolCode = #SymbolCode)
What is the option in mongodb filter
var filter = new BsonDocument
{
{
"symbolCode", SymbolCodeSearchString // If string SymbolCodeSearchString is blank, it should retrieve all data else the search data
}
};
Sample Data
{
"_id": {
"$oid": "60ed91bc65675f966c0eec46"
},
"symbolCode": "F",
"timestamp": {
"$date": "2021-07-13T13:14:35.909Z"
}
}
you should check symboleCode before query on mongodb
first check if symbolCode is empty or ""
define filter query as
var filter = new BsonDocument
{
};
else if it was not empty
var filter = new BsonDocument
{
{
"symbolCode", SymbolCodeSearchString // If string SymbolCodeSearchString is blank, it should retrieve all data else the search data
}
};
I was able to figure out. Thanks to #Naimi and #Takis. Building a dynamic filter is the key. Posting here the answer so that it could help anyone
var filterQuery = new BsonDocument
{
{
"symbolCode", new BsonDocument
{
{ "$regex", SymbolCodeString},
{ "$options", "i"}
}
}
};
if (fromDate != "" && toDate != "")
{
BsonElement dateFilter = new("timestamp", new BsonDocument
{
{ "$gt", fromDate},
{ "$lt", toDate}
});
filterQuery.Add(dateFilter);
}
By this way, i am able to add any number of filters dynamically
I cannot see data matching status and name this way. When I run this, the status and name are searching separately. but I want to get the data matching both.
return await Product.find({
$or: [
{ status: args.status },
{ product_name: args.product_name}
]
}).sort({ createdAt: "desc" });
I tried filter and aggregate but I could not get the correct data.
status can be null. $and it doesn't work for me.
solved
let filter = {};
if (args.status) {
filter.status = args.status;
}
if (args.product_name) {
filter.product_name = args.product_name;
}
const result = await Product.find({
...filter
}).sort({ createdAt: "desc" });
return result;
If you want to find products where status == args.status and product_name == args.product_name you would pass a query object like this:
{
status: args.status,
product_name: args.product_name
}
Edit
It sounds like you want to build the filter document depending on available parameters. It might look something like this.
let filter = {}
if (args.status) {
filter.status = args.status
}
if (args.product_name) {
filter.product_name = args.product_name
}
You would then pass this filter object to the find call.
Through Flutter I want to add a Map element in Firestore.
Instead of fetching the whole map and replacing it with the added element is it possible to directly add a new key and value?
Example:
Map = { '2020-05-21' : true } -- Add --> Map = { '2020-05-21' : true, '2020-05-22': true }
This is how I tried to do this but without any success.
return collection.document('id').updateData({'map.$date' : true});
Use this approach:
final ref = Firestore.instance.document('collection_id/document_id');
await ref.updateData({
'field.key2': 'value2',
});
Since I am not having an idea about how your data looks like on server, I tested this one and it worked.
Edit:
// initial work
var ref = Firestore.instance.document('Employees/54G...Naf');
var initialData = {
'date_1': '1',
};
await ref.setData({
'busy_map': initialData,
});
// updated work
var updatedData = {
'busy_map.date_2': '2',
};
await ref.updateData(updatedData);
I have changed the object structure from
{
id:"...",
name:"...",
url:"...",
studentAccess:{
"A":"....",
"B":"...",
},
ecosystemId:"..."
}
TO:
{
id:"...",
name:"...",
url:"...",
studentAccess:[
{
"X":"....",
"Y":"..."
},
{
"X":"....",
"Y":"..."
},
{
"X":"....",
"Y":"..."
},
],
ecosystemId:"..."
}
in API we get list of these objects based on ecosystemid or student access item "X", name or any field..calling like this in API
var acc = await _eco.FindByUser();
var query = await _db.CourseDocuments.FindAsync(w => w.EcosystemId == acc.Identifier);
after query executes i get this error pls help me i need to change structure anywhere after it changed in mongoDB?
I'm actually building a simple application in meteor that's taking a weapon's skin thought my steam inventory, parse the weapon's market hash name, and finally return the median price of the skin according to the steam market. My problem is about storing the price of the skin, I use this npm package that I have included in Meteor (I followed the asynchronous way) and I can easily get the skin's price. I put this code into a Meteor method on the server-side, like this :
Meteor.methods({
getPrice:function(weapon,skin,state,loteryRef)
{
var csgomarket = Meteor.npmRequire('csgo-market');
var Q = Meteor.npmRequire('q');
var wears = [state];
var data = {
prices : [{
weapon : weapon,
cached : false,
skins : [skin],
skinData : {},
price : '',
}]
}
var getPrice = function(theData) {
var promises = [];
theData.skins.forEach(function(skin) {
theData.skinData[skin] = {};
wears.forEach(function(wear) {
promises.push(csgomarket.getSinglePriceAsync(theData.weapon, skin, wear, false).then(function(data) {
theData.price = data.median_price;
}));
});
});
return Q.allSettled(promises).then(function() {
return theData;
});
}
getPrice(data.prices[0]).then(function(results) {
console.log(results.price);
});
}
});
The result of the promise's function getPrice(data.prices[0]).then(function(results) {}); can only be console.logged and I can't save results outside of this function. When I try to perform an insert in this function for saving this value, it doesn't work too. What I'm doing wrong ?
Please forgive me for my quite good English