This is the screenshot of my database.
I want to fetch the record for a particular username. (For eg: where user=nam#gmail.com) Can anyone suggest to me how to fetch this in flutter?
It would be a great help, Thank you.
To get the data, you can create a function like:
Future getData(String username) async {
List dataList = [];
try {
await FirebaseFirestore.instance.collection('userdata').where('user', isEqualTo: username).get().then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
itemList.add(doc.data());
}),
});
return itemList;
} catch (e) {
print(e.toString());
return null;
}
}
When you'll call this function, you will have to pass the username and it would return a list of data items.
This list can then be used to show data in the UI as:
child: Text(
title: Text(subjectList[index]['user']),
),
you can try this approach it helped me, but if you have migrated to null safety just make sure that you change the code accordingly
You can try the following query to get your result.
FirebaseFirestore.instance
.collection('your-collection-name')
.where('user', arrayContains: 'nam#gmail.com')
.get();
For android solution follow this:
FirebaseFirestore.getInstance()
.collection("users").whereArrayContains("user","nam#gmail.com").get();
Related
I've been recently trying to code in a Discord bot currency system using Sequelize, but the code that I wrote to make items usable for a server doesn't seem to work.
I mostly want it so that if I type in d!use the server member can use the item.
Here's a bit of the code I've written:
UserItems.belongsTo(CurrencyShop, { foreignKey: 'item_id', as: 'item' });
const userItem = await UserItems.findOne({
where: { user_id: this.user_id, item_id: item.id },
});
if (!userItem) {
return message.channel.send("You don't own this item!");
} else {
return message.channel.send(`You used ${item}`);
await user.removeItem(item);
}
Much thanks in advance!
If the removeItem() method is correctly typed, the only problem here is that you are returning the message.channel.send before using the removeItem() method and that causes the resulting if-else statement before removing the item from the database.
Try to change if-else statement to this:
if (!userItem) {
return message.channel.send("You don't own this item!");
} else {
message.channel.send(`You used ${item}`);
return await user.removeItem(item);
}
I have a paginated cursor based query TODOS and detail page with query TODO to get data by ID.
Whenever I go to detail view and use useQuery with TODO query (Which contains exactly same data as TODOS query result, it still tries to get data from server not from cache. How can I achieve to not get data from server (Because it already exists), I thought Apollo detect by id and return from the cache but no. Any suggestions ?
Similar issue as no this post, but I don't think thats a right approach, there should be better solution. (I hope)
This is TODOS query:
query TODOS(
$paginationOptions: PaginationOptionsInput
) {
todos(paginationOptions: $paginationOptions) {
pagination {
minCursor
maxCursor
sortOrder
limit
hasMoreResults
}
result {
id
...SomeTodoFields
}
}
And on detail page I have second query TODO
query (
$todoId: String!
) {
todo(todoId: $todoId) {
id
...SomeTodoFields
}
}
Since I am using Apollo-client < 3.0 for me cacheRedirect worked fine, you can have a look farther here. Read every note carefully it is really important! My code example:
cache: new InMemoryCache({
fragmentMatcher,
cacheRedirects: {
Query: {
todo: (_, args, { getCacheKey }) => {
return getCacheKey({ __typename: 'TodoType', id: args.todoId })
}
}
}
})
})
Found some good relevant article as well, which you might want to check.
This worked for me, hope it helps to someone else as well. :)
fire.firestore().collection('Customer').get()
.then(data=>{
data.docs.forEach(doc=>{
let db = fire.firestore().collection(`Customer`)
db.where("updated", ">=", 0).limit(100).onSnapshot(async doc=>{
try {
await doc.docs.map(each=>{
setDatas([...datas, {...each.data()}])
})
}
})
})
I am trying to append the object in the array to query from firestore.
However, somehow it only reads last document.
Please help me if you could store state without using array.
Checking your code and running this data as sample I could notice your code is getting all the results and not just the last one, so there could be something else. Also it seems like a double unnecessary query.
Instead you can query all the docs you may want to get them using .. where("updated", ">=", 0).limit(100) .. and not a query inside a query.
You can use the sample code from here to make something more simpler:
const admin = require('firebase-admin');
admin.initializeApp();
let db = admin.firestore();
const citiesRef = db.collection('Customer');
const snapshot = await citiesRef.where('updated', '>=', 100).limit(100).get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
//Your code here to add to your array
});
This code is for NodeJS but you can adapt it to ReactJS
So i am curious when does onDataChange method occur?
It seems like it is activated when user add new information or change already existed data.
However, what I am trying to do is that, before adding new data, I want to check if the item is existing in database....if there is an identical item, adding new data won't be done, or if there is no such item, then it should be added to database.
so, my actual question is that, this process "Checking all the database items", can it be done without using onDataChange method?
You basically set up a subscription to the "onDataChange" so its actually watching firebase for changes.
But for checking you could literate through the results or do one time query to the exact path your data it held at.
It also may be a better choice to record everything and then remove the data when not needed.
import { AngularFirestore } from 'angularfire2/firestore';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { map } from 'rxjs/operators';
import { Observable, Subscription } from 'rxjs';
import firebase as firebase from 'firebase/app';
private mysubscription: Subscription;
public this.items:any = [];
constructor(
public _DB: AngularFireDatabase
) {
try {
//subscription using AngulaFire
this.mysubscription = this._DB.list("myFireBaseDataPath").snapshotChanges().pipe(map(actions => {
return actions.map(action => ({ key: action.key, val: action.payload.val() }));
}))
.subscribe(items => {
this.items = [];
this.items = items.map(item => item);
console.log("db results",this.items);
var icount=0;
for (let i in this.items) {
console.log("key",this.items[i].key);
console.log("val",this.items[i].val);
console.log("----------------------------------);
//checking if something exists
if (this.items[i].key == 'SomeNodePath') {
var log = this.items[i].val;
}
}
} catch (e) {
console.error(e);
}
});
}
ngOnDestroy() {
this.mysubscription.unsubscribe();
}
//or we can do a one time query using just the firebase module
try {
return firebase.database().ref("myFireBaseDataPath").once('value').then(function(snapshot) { return snapshot.val(); })
.then(res => {
for (let myNode in res) {
console.log(res[myNode]);
console.warn(res[myNode].myChildPath);
console.log("----------------------------------);
}
})
.catch(error => console.log(error));
} catch (e) {
console.error(e);
}
//however it may be better practice to log all data and then firebase.database().ref(/logs").remove(); the entire log when not needed
var desc ="abc";
let newPostKey = firebase.database().ref("/logs").push();
newPostKey.set({
'info': desc,
'datetime': new Date().toISOString()
});
When does onDataChange method occur?
The onDataChange method is called for every change in the database reference it is attached to. It is also called for every visit to the database reference it is attached to.
For example,
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("some/database/refrence");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method will be fired for any change in the
database.getReference("some/database/refrence") part of the database.
// It will also be fired anytime you request for data in the
database.getReference("some/database/refrence") part of the database
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
// This method will be fired anytime you request for data in the
database.getReference("some/database/refrence") part of the database
and an error occurred
}
});
Before adding new data, I want to check if the item is existing in database....if there is an identical item, adding new data won't be done, or if there is no such item, then it should be added to database.
This can be done by calling the exists() method on the snapshot retrieved from your database query.
Check this stackoverflow question Checking if a particular value exists in the firebase database for an answer to that
So, my actual question is that, this process "Checking all the database items", can it be done without using onDataChange method?
No. The onDataChange method is the callback used to retrieve data from the database. Even if you use the equalTo() method on a query, you'll still have to use the onDataChange method.
I am not a Firebaser Specialist tho. There are folks who work at Firebase on here. They could give you more information
PS: Please make your own research on your questions first before asking. Some questions are already answered in the documentation and on stackoverflow.
I have a problem with Flutter and Cloud Firestore from Firebase.
I already can add data to the database but I can't fetch it, because every time I call my method I get null back.
Here is my code:
dynamic getFromDatabase(String path, String item) {
DocumentReference _docu = Firestore.instance.document('$path');
var data;
_docu.get().then((datasnapshot) {
if(datasnapshot.exists){
data = datasnapshot.data['$item'];
}
});
return data;
}
This is where I call the method:
print((await getFromDatabase("User/$_uid","Vorname")));
And the error:
I/flutter (26289): null
I've not used Firestore before. Only the normal database of firebase. But I think this is a async timing issue. It looks like it's returning null before it can complete the datasnapshot. (PS. datasnapshot is spelled wrong). Try something like this. Like I said. Not sure if it works.
Future<String> getFromDatabse(String path, String item){
DocumentReference _docu = Firestore.instance.document(path);
_docu.get().then((datasnapchot){
if(datasnapchot.exists){
return datasnapchot.data[item];
}
});
}
And when calling the method. Do this.
String getData = await getFromDatabse(path, item);
(PS also database is spelled wrong haha)
A good option is using the FutureBuilder widget.
You can use it inside a StatelessWidget, avoiding to implemente a StatefulWidget
FutureBuilder(
future: Firestore.instance.document(path).get(),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Something went wrong.');
}
DocumentSnapshot docSnap = snapshot.data as DocumentSnapshot;
return Text(docSnap.data['doc_field']);
}
)