firebase realtime db checking a record for exist [duplicate] - firebase

This question already has answers here:
Test if a data exist in Firebase
(3 answers)
Closed 4 years ago.
I am using angularfire2 wth my ionic app and have sign in with facebook enabled.
When first time a user logs in using the fb then i naturally dnt have any record of it in my firebase DB. I want to create a user node using the facebook returned uid as the node.
The way i can retrieve it is like below. I can check by seeing if it has child objects etc. But is that the way recommended to do this kind of checks? I also don't see how to add subscribe or then to it as i would assume this should be async operation for me to wait until it confims me that user does not exist yet. Please advise
const userRef = this.db.object("/users/" + uid)

Simply building a reference to some location in the database (as shown in the code above) says nothing about whether or not data exists at that location. The location needs to be queried in order to figure out of data exists there.

The sample code get from firebase web API document.
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});

Related

How to avoid entering a repeated data in firebase documents?

My database is quite simple. A collection and inside, there are documents with user information, including their username.
(I am doing this in flutter and firestore).
What I want is to prevent two users from having the same username.
I am doing this to insert the data.
FirebaseFirestore.instance.collection('users').add({
'username': 'username',
'desc': 'some bio',
'fieldone': 'aaa',
'fieldtwo': 'bbb',
// other user info
});
And to consult the data of a user (by their username).
FirebaseFirestore.instance.collection('users').where('username', isEqualTo: 'username').get();
At the moment I insert the data, what can I do to verify that said username is already in the database?
So if the username already exists, return an error and don't let insert it. And if it doesn't exist yet, it can be inserted.
What query can help me for this?
I am new to firebase. :(. Thanks.
What query can help me for this?
This can't be accomplished by a single query. You will have to take the steps you outlined already in your question. You will have to first query for documents with that username, then only insert a new one if there were none found.
However, you should be aware that there is a race condition here. If two people are trying at the same time to add the same username, it's possible that they both end up adding a document.
The only way to ensure uniqueness in Firestore is using the document ID. You might want to consider using the ID of the document to store the username (or some version of it, like a hash) so that a race condition can never occur, and that you only have one document with that username.
See also:
Firestore unique index or unique constraint?
Cloud Firestore: Enforcing Unique User Names
Unique field in Firestore database + Flutter
firebase rule for unique property in firestore
As you can see, your issue has already been thoroughly discussed on Stack Overflow.

Use Firestore autoID to retrieve and display data in Flutter

im new to flutter and dont know exactly what to search for this one but, can we use the auto generated ID like in the picture to retrieve all that data UNDER that ID? if so, how ? In a similar question that I stumbled upon, they use database.reference() but its a Realtime Database and not FireStore
Im using Firebase Cloud Firestore
There is no AutoId in firebase but here is a quick way to set as auto id
Forexample ;
1- create yourModel ( which one u gonna send as model to firebase )
2- DatabaseReference firebaseDatabase;
3- firebaseDatabase =FirebaseDatabase.instance.reference();
4- firebaseDatabase.child("table_name").push().set( yourModel.toJson() );
Also for getting data u can write code like that
var result= firebaseDatabase.child("table_name").once().then(
(DataSnapshot datasnapshot){
Map<dynamic,dynamic> values= datasnapshot.value;
values.forEach((key,value){
print("key:"+key+" value:"+value["name"]);
});
}
);
print(result);
I tried it and works great
Have a nice day !!!
I'm guessing you're asking about subcollections.
If you read a document (by its (auto-generated or not) key), you get back that document. You don't get back data from any subcollection. That will require a separate read operation for each subcollection under the document that you want to read.

Fetch documents from multiple subcollections - Firebase [duplicate]

This question already has answers here:
Firestore query subcollections
(11 answers)
Closed 3 years ago.
I'm creating a web app for admin with firebase integration, this web app is used by admin to monitor posts or comments posted by user from Android or iOS app developed in ionic.
I'm using Firebase firestore, and following is the database design
posts/{postsDocument}/comments/{commentsDocument}.
The comments here is sub-collection for postsDocument that holds all the comments for a particular post. Also postDocument and commentsDocument contains Firebase uid of the user.
My problem is, whether it's possible to fetch all the comments commented by a particular user. I can query a single collection, but in this scenario commentsDocument is a subcollection and i want to fetch all comments across all the post by a user for monitoring purpose.
You can check firebase collection group query
var commentsQuery = db.collectionGroup('comments').where('commentOwnerID', '==', userId);//userId - firebase id of the user who commented
commentsQuery.get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
});
});
Also you might have to create index that supports your query, check console for the the link for creating index

Firebase database functions onWrite/Create/Delete user UID [duplicate]

This question already has answers here:
Getting the user id from a database trigger in Cloud Functions for Firebase?
(2 answers)
Closed 5 years ago.
Is is possible to get the user UID of the user who wrote/updated/deleted data from the database?
When you are using Firebase authentication you can get the uid of the authenticated user using the following lines of code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String uid = firebaseUser.getUid();
}
On the other hand, you need to know that Firebase does not store meta-data or other informations regarding write operation. To achieve this, you need to create your own mechanism.
In your case, when a user creates a record, store his uid on a location from where you can query for that particular uid and use it for what you want.
In case you are trying to determine this within Cloud Functions i recomand you take a look at Firebase Cloud Functions and at jacobawenger's answer from this post

Firebase Database Unity differentiating between old and new data

I am building a chat engine using firebase in unity. I want to differentiate between the existing data and all the new data that gets added into the database. There is method once in web sdk of firebase which helps in differentiating between old and new data, is anyone aware if we have something similar on unity
There is no direct way to do this, one way that is a workaround is to add a timestamp value in all the entries maintained in the database and each time one subscribes for the new data we make use of the OrderByValue|OrderByKey and StartAt to do the same.
In the beginning value for StartAt will be 0 but post that whenever a child gets added we can update the StartAt value to that so that the next time client subscribes for the childAdded, it will only receive data post the last child.

Resources