I want to save users data in firebase , should I save theme as map in database like this:
[
{
"id":1
"name":"ab"
"age" : 34
}
{
"id":2
"name":"aab"
"age" : 4
}
{
"id":3
"name":"aeb"
"age" : 25
}
]
or there better idea to do that?
I would suggest use FireStore for such data.
These types of incremental approaches aren't possible in firebase firestore. Alternatively, you can use a firebase function to add id while creating a new user. When a new document has been created the function will call the previous user-id as an integer and increment the id number by 1 and post it as the next user-id. But if you want to have the feature to delete the user document in the future then the id will be also removed as usual.
Related
I have collection called 'services' inside every document I have 4 fields :
name
description
userID
Rating
and I want to give only the user to change his profile except rating I want to make it accessible (can update) to everyone , I check some problem like that and I get one solution that is create sub collection in profile doc I call it "rating" that contain a doc with the name "rate" and I make only this sub collection accessible to update from everyone ,
but I don't know how to to get subcollection data from a doc any solution plz with this rating problem :
My security rules after creation a sub collection for rating :
match /{category}/{serviceid} {
allow read,create;
allow update : if resource.data.userID == request.auth.uid;
match /rating/rate {
allow read,write;
}
}
I get all services with const docs =db.collection("categoryname").get() :
and I fetch every item data like that :
docs.foreach(doc => doc.data().name)
How can I get subcollection("rating") data from the doc?
You realize that with these rules, you allow everyone access? Even people unauthenticated would be able to make unlimited writes. Is that what you really want?
To answer your question, to access to the /rating/rate document you could just do:
let category = "categoryname";
db.collection(category).get()
.then(function(querySnapshot) {
querySnapshot.foreach(
function(doc) {
let serviceid = doc.id;
db.collection(category).doc(serviceid).collection("rating").doc("rate").get()
.then(function(doc) {
... // do whatever
}
}
)
}
You can also check the Official Documentation to get a document.
I have a firebase database like this structure:
-groups
--{group1id}
---groupname: 'group1'
---grouptype: 'sometype'
---groupmembers
----{uid1}:true
----{uid2}:true
--{group2id}
---groupname: 'group2'
---grouptype: 'someothertype'
---groupmembers
----{uid1}:true
----{uid3}:true
----{uid4}:true
Now, I am trying to pull groups of authenticated user. For example for uid1, it should return me group1id and group2id, and for example uid3 it should just return group2id.
I tried to do that with this code:
database().ref('groups/').orderByChild('groupMembers/' + auth().currentUser.uid).equalTo('true').on('value' , function(snapshot) {
console.log('GROUPS SNAPSHOT >> ' + JSON.stringify(snapshot))
})
but this returns null. if I remove "equalTo" and go it returns all childs under 'groups'.
Do you know any solution or better database structure suggestion for this situation ?
Your current structure makes it easy to retrieve the users for a group. It does not however make it easy to retrieve the groups for a user.
To also allow easy reading of the groups for a user, you'll want to add an additional data structure:
userGroups: {
uid1: {
group1id: true,
group2id: true
},
uid2: {
group1id: true,
group2id: true
},
uid3: {
group2id: true
},
uid3: {
group2id: true
}
}
Now of course you'll need to update both /userGroups and /groups when you add a user to (or remove them from) a group. This is quite common when modeling data in NoSQL databases: you may have to modify your data structure for the use-cases that your app supports.
Also see:
Firebase query if child of child contains a value
NoSQL data modeling
Many to Many relationship in Firebase
is it possible to insert battery_cost_change: field multiple time with counter value in firebase in same user Message Which is LM2JKCacawaW7tlK4yK. like battery_cost_change1: ,battery_cost_change2:,battery_cost_change3: and so on And how these fields will be retrieve in android programmaticallyenter image description here
You may wish to consider the db structure for battery_cost_changes to hold multiple instances of battery_cost_change object.
Everytime you add a new battery_cost_change - you can push the object into the path .../LM2JKCacawaW7tlK4yK/battery_cost_changes. <pushId> is the random ID Firebase generates, when an object is pushed/added into the node.
{ LM2JKCacawaW7tlK4yK: {
....
battery_cost_changes: {
<pushId>: {
battery_cost_change: 6
},
<pushId>: {
battery_cost_change: 3
}
}
....
}
While retrieving the values, you can read the path .../LM2JKCacawaW7tlK4yK/battery_cost_changes and observe the values for an array of battery_change_cost objects. Please share more details, to explore a better or more suitable answer. However, I feel this is a generic idea to store multiple values under a node.
I'm trying to setup a friend system in Firestore. My data model looks like this at the moment:
collection("users") ->
document("user1")
document("user2")
...
A document in the users collection contains data like the name, email... of the user. I'd like to enable a user to have friends now, but I'm unsure about the best way to model this.
So, I'd for sure add a friends field in the documents of the users, but what should this field contain? My first thought was a pointer to a new collection called friends in which the documents are users. Something like this:
collection("users") {
document("user1") {
name:user1,
friends: -> collection("friends") {
document("user2"),
...
}
}
}
This seems reasonable, but that'd mean that I'd have a lot of duplicate data in my database because each user that has friends will be duplicated in a friends collection. Should I worry about this or is this normal in a Firestore database structure?
Would it perhaps be possible to point to a document in the users collection from the friends collection? Something like:
collection("users") {
document("user1") {
name:user1,
friends: -> collection("friends") {
document, -----
... |
} |
}, |
document("user2")<-
}
Or should I throw away the thought of using a collection for friends and just keep a list with uids of all friends of the user?
Seems you are using two separate collections for users and friends first all you can do it by one collection. But I don't want to go there may be there was another scenario.
As your separate collection way, you can design your friends collection model to meet no duplication:
{
name : 'Name',
email : 'email#mail.com'
has_connected : {
'user1' : true // here you can use anyother unique key from user
}
}
The thing is that firestore recommend this types of design for query and for faster performance you can make that has_connected key as index.
In this approach, you have to check during adding new friend by email or any other unique key. if exists then just put another key into has_connected with the respective user. e.g user2 : true.
Finally, for fetching all friends for a user you have to do a query like this: e.g: in javascript
let ref = firebase.firestore().collection("friends");
ref
.where(`has_connected.${username}`, "==", true)
.get()
.then(//do your logic)
.catch()
Thanks
In my app I create a default array of data upon user registration and add it under that user id in the following manner (using a service):
function addDefaultData(){
var defCategories = ['','data1',
'data2',
'data3',
'data4'];
var updates = {};
updates['/user-data/' + firebase.auth().currentUser.uid + '/' + 'categories'] = defCategories;
return firebase.database().ref().update(updates);
}
}
After registration the user can change this array, add or remove single item at a time. I read here but that does not help me. This is how the data looks in firebase db:
-appName-fomefirebaseid123
-user-data
-userID123687FHGJH4546HGJ
+5_2017
-categories
0: ""
1: "data1"
2: "data2"
3: "data3"
4: "data4"
How can I manipulate this array? Remove or add new items to it?
The Firebase team believes that "Arrays are Evil" (see: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html).
In that same article, they state: "Firebase has no native support for arrays. If you store an array, it really gets stored as an 'object' with integers as the key names."
I'd read the above blog and adjust my expectations and approach to interacting with Firebase accordingly.
In your case, if you want to delete index "0" of categories, you're really deleting key "0" of the categories document.