Compare 'currentUser?.uid' To childByAutoIds - firebase

Using firebase and Swift. Is there any way of comparing the current user:
'let uid = Auth.auth().currentUser?.uid'
with the autogenerated id's under 'Users' or 'Advertiser' in the Firebase Structure?
I want to do a If statement and see if the currentUser matches with the Id's under Advertiser or Users.

If you're trying to check if a certain node exists in the database, that should be a fairly simple with something like:
Database.database().reference(withPath: "Advertiser").child(uid)
.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() ...
Also see:
Swift Firebase Check if user exists

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.

Firebase realtime database filtering data

so here i have
So I am making dating app, and now i come to the moment, where i need to create a list of people to match with for user.
So I need a firebase query to look in to gender and check if the people already matched, if yes it should not be included in the list.
I tried, filtering data by gender. How I should edit this query to check if they already matched?
Matches are displayed in users/{userID}/matches/{matchedUserID}
This is what i tried:
async createUserListAndNavigate() {
let genderTolook = 'female';
let data = firebase
.database()
.ref('users/')
.orderByChild('gender')
.equalTo(genderTolook);
data.once('value', snapshot => {
console.log(JSON.stringify(snapshot.val()));
});
}
You can use the array-contains-any query to check if the matches array already contains the user_id.
var users = db.collection("users");
users.where('tempuser.matches', 'array-contains-any', [<USER_ID_TO_MATCH>]);
Based on the result you can make further queries/operations. You could also combine this query with other queries.
See the documentation for further details.

How can I assign content to specific signed in user within Flamelink and React Native?

I am using Firebase with React Native and just started with Flamelink as my CMS.
Before using Flamelink, I was able to obtain specific content from a logged-in user via firebase realtime database because the schema was:
**fruits**
mwaKRypUrNb8rJdsj9YUxw0sA892
-M055RlZ7HBzgRD9LS1d
-M055Why2psB2kqE4mYO
-M05W3LK8C1kgFsPNRqa
-M05W47cbhJ2VA_Y2nnT
-M05W5Wu9Pp6TZJJPc8t
-M05W6Xc_iP1upbyENpj
-M05W7JnVt3t3DsjNaRT
-M05W8OuZph-1gDDY9UX
-M05W9Fws0_hsNCAyKDt
**users**
-zFWGnGhEmbfhjAJsUT99ZbkJBZ33
As you can see, the fruits schema had user-specific content.
With Flamelink the schema looks like this:
**flamelink**
--environments
----production
------content
--------**fruitEntryForm**
----------en-US
------------1582070066847
------------1582074440836
------------1582080914427
**schemas**
**media**
**permissions**
**settings**
**users**
--zFWGnGhEmbfhjAJsUT99ZbkJBZ33
My react native code is below:
const user = navigation.getParam("user");
const currentUserData = await firebase
.database()
.ref("flamelink/users")
.child(user.uid)
.once("value");
const fruits = await app.content.get("content");
How can I modify Flamelink so that I can manage content based on which user is signed in?
From my understanding, your Fruits collection can be linked to multiple users and the main problem is that the Firebase Realtime Database does not allow querying for a value inside an array. Cloud Firestore is a bit better in that regard.
What I would suggest you do to simplify your queries is to turn the relationship on its head. I would have the Fruits collection that you currently have without a relationship to any users. Then I would create a "Users Fruit" collection that has a field for the user's UID with a relational select field that maps to multiple entries in your Fruits collection.
From your React Native app, you can then use our SDK to query the "Users Fruit" collection and expand the related Fruits.
Depending on the version of the SDK you are using, the syntax might differ a bit, but for the latest SDK it will look like this:
const userFruit = await app.content.get({
schemaKey: 'usersFruit', // assuming schema key is this
orderByChild: "user", // assuming your field is called 'user'
equalTo: "mwaKRypUrNb8rJdsj9YUxw0sA892", // assuming this is your user's uid
populate: ['fruits'] // assuming you called the select relational field 'fruits'
})

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.

Find object in Firebase by one value

I have next database list (usernames + user id).
How can i find object by user id and change his key (username)?
I'm using AngularFire2 with Angular 5.
You can find a child node by its value with a query like this:
var users = firebase.database().reference("usernames");
var query = users.orderByValue().equalTo("Sk6I..."ltA2");
By attaching a listener to this query you'll be able to find the reference and the key of the user (or "any users", since technically there may be more keys with the same value) matching the UID.
But you can't rename a node. You'll have to remove the existing node, and create a new one. For more on this see:
Firebase: Update key?
Firebase API for moving a tree branch from a collection to another one
Is it possible to rename a key in the Firebase Realtime Database?
Solution for my case:
this.db.list('usernames', ref => ref.equalTo(uid)).remove() // Remove old value
this.db.list('usernames', ref => ref.equalTo(uid)).set(
username, uid
) // Create new value

Resources