How to get firebase id - javascript

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}

The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.

Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.

but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

Related

Is it possible to get document id of collections available in Firebase Cloud Firestore database?

I want to get the document id of societies collection in cities collection but my code returns a different id in societyId field in the cities collection.
myId: string = "";
private docRef: firebase.firestore.DocumentReference;
this.docRef = firebase.firestore().collection("societies").doc();
this.myId = this.docRef.id;
this.cityList = firebase.firestore().collection("cities").add({
cityName: this.city,
societyId: this.myId
}).then((doc) => {
console.log(doc);
}).catch((err) => {
console.log(err);
});
You are getting another societyId, which is different than the id that is generated by simply calling doc() function because you are adding an object to the database using CollectionReference's add() function:
Adds a new document to this collection with the specified data, assigning it a document ID automatically.
Instead of using DocumentReference's set() function:
Writes to the document referred to by this DocumentReference. If the document does not exist yet, it will be created. If you pass options, the provided data can be merged into the existing document.
According to your comment, if you want to have the same id, please change the following line of code:
this.cityList = firebase.firestore().collection("cities").add(/* ... */);
to
this.cityList = firebase.firestore().collection("cities").doc(this.myId).set(/* ... */);

How to access firebase db sub object elements?

My firebase db structure is given below,
users
fb-user-key1
user1-details1
Tags
Tag-key1
"name":"value"
Tag-key2
"name":"value"
fb-user-key2
user1-details2
Tags
Tag-key1
"name":"value"
Tag-Key1 & user-key's are generated by firebase with push(). firebase code to access the content is,
var fbref = firebase.database().ref("users");
fbref.child("Tags").on("child_added", function(e){
var Tagobj = e.val().name;
console.log(Tagobj);
});
This one is not returning anything. I am not able to access name:value pair in the above data structure.
`
adding modified code,
firebase.database().ref("users").on("child_added",function(eā€Œā€‹) { var Tagobj = e.val().Tags; });
Output of the above code is output data structure
How to access that name value pairs?? firebase keys are issue?
Not getting, where I am wrong. Appreciate your inputs.
Since Tags is a child property of each user, then you have to read it off of each user object.
If you want all Tags for all users, assuming Tags for each user is not updated after a user is created, you can do this:
tagsPerUserId = {};
firebase.datatabs().ref('users').on('child_added', function(snap) {
tagsPerUserId[snap.key] = snap.value().Tags;
// TODO: Notify view that tagerPerUserId is updated and needs to be re-rendered
console.log(`Tags for userId ${snap.key}: ${snap.value().Tags}`);
});
This way you will also get Tags of new users when they are created, but you will not get updates to Tags of existing users.

How to query Firebase data after using .push() to add data?

Here is the code for when I'm pushing the data to Firebase:
firebase.database().ref(`booklogs/${uid}/${book_id}`).push(page_id)
booklogs :
{HUMjSHxVKAPfVXzOId9zCBkGOgv1:{
book28917: {
-KYp4FdYYODDZG1FX-Pb: 1
}
}
}
My problem is when I query the data, the child node of the ${book_id} includes the push key, but I only want to get the value which is 1 and not the push key.
The code I use to query is:
var booklogs = db.ref(`booklogs/${uid}/${project}`);
booklogs.once('value')
.then((snapshot) => {
console.log(`pages viewed are ${snapshot.key}: ${snapshot.val()}`);
console.dir(snapshot.val());
}).catch((error) => {
console.log(`Error : ${error}`);
});
The data returned in the console is:
pages viewed are 2634651: [object Object]
{ '-KYp4FdYYODDZG1FX-Pb': 1 }
Any input would be much appreciated. Thanks!
If you only want the '1' and not the push key, try using .set()
firebase.database().ref(`booklogs/${uid}/${book_id}`).set(page_id)
That will get rid of the object and just give you the value that you wanted. Push automatically generates a key for every value you add, so you will always get an object back. From the Firebase docs - "For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path."
https://firebase.google.com/docs/database/web/read-and-write

Javascript / Parse: Follow wont return 'to' value

I am trying to get all of the users that are following the current user. From some reason Parse returns the username as undefined in the 'to' field but I am able to retrieve the user name from the 'from' field like so:
var query = new Parse.Query("Follow");
query.equalTo("to", Parse.User.current());
query.find({
success: function(users){
for (var i = 0; i < users.length; i++) {
console.log(users[i].get('from').get('username')) // returns current username
console.log(users[i].get('to').get('username')) / returns undefined
}
}
});
But those values do exist and there is a username. I am able to get the value using the fetch method but I am curious as to why this approach doesn't work. Thoughts?
From Doc, you're not getting the actual object, but the ref to that object:
Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency. ......
And
By default, when fetching an object, related Parse.Objects are not
fetched. These objects' values cannot be retrieved until they have
been fetched like so:
// Here, post is something similar to your `users[i].get('to')`
var post = fetchedComment.get("parent");
// So you need to fetch it again to get its real object.
post.fetch({
success: function(post) {
var title = post.get("title");
}
});
So what you get from users[i].get('to') is a reference to that user object. You can either fetch it again.

Accessing Firebase push() child

I'm slowly getting into Firebase but have what is probably a stupid question. If I am adding children to a reference using push(), how do I retrieve/delete them if I don't save the generated push ID?
For example, take this root:
var ref = https://myaccount.firebaseio.com/player
And if I write a new entry to /player:
var new_player= ref.push({
name:"User",
country:"United States"
})
Firebase generates a push ID for that:
https://myaccount.firebaseio.com/player/-JxgQCQsSLU0dQuwX0j-
which contains the information I pushed. Now lets say I want to retrieve or remove that player? Should I store the generated ID as a child of itself using .key() and .set()?:
//this will get -JxgQCQsSLU0dQuwX0j-
var _newPlayerKey = new_player.key();
//updates the record I just created
var update_player = ref.set({
name:"User",
country:"United States",
ref: _newPlayerKey
})
I don't see how else to access that object by it's generated ID... is there a better way to set this up?
Why are you doing that can't use the key() method, it should be adequate in almost all cases i.e.
playersRef.limit(10).on('child_added', function (snapshot) {
var player = "<p>"+ snapshot.val().name +" <button data-value='"+snapshot.key()+"'>Delete</button></p>";
$(player).appendTo($('#messagesDiv'));
});

Categories

Resources