I have a problem and I want to modify some information not all, for example I want to modify only the address and the nit (see image) but in doing so I delete the other fields, how could I modify it without eliminating the rest?
image
My code:
var uid = firebase.auth().currentUser.uid;
var modi = {
nombre: "Hello",
direccion: "Address"
}
var updates = {};
updates['/Users/' + uid] = modi;
firebase.database().ref().update(updates);
Thank, you!
Do you have access to that User object data?
If so, basically merge the updates into that and then save to Firebase. E.g.
// if we already have some reference to User data object
var updates = {...userObject, ...modi};
firebase.database().ref('/Users/' + uid).update(updates);
else you can always fetch that object, then do the merge and update procedure above. E.g.
// modi defined above
return firebase.database().ref('/Users/' + uid)
.once('value')
.then(function(snapshot) {
var user = snapshot.val()
updates = {...user, ...modi}
firebase.database().ref('/Users/' + uid).update(updates);
});
Related
I am trying to update a User in Firebase using Angular 4 with AngularFire2. In the user object that tis saved to the firebase database, I want to insert another object into an array property. In my service I am trying to do this functionality (I already have everything in keys etc also)
generateUserCharacterList(){
this.genCharList = new CharacterList(x, y, z)
this.UserListOfCharacters.push(this.genCharList)
//Other code...
}
This does not work though
The Update specific fields documentation indicated usage of the .update method.
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
I am considering that you are using the firebase realtime database as compared to the firestore.
You should take the value of the array in a variable, change the value, and then call the update method on the object ref with that new value. Here is the code sample for the explanation:
let userRef = db.object('users/aad1asd123-123asd');
let user = userRef.valueChanges();
let listOfChars = user.listOfChars;
listOfChars.push('a');
listOfChars.push('b');
listOfChars.push('c');
listOfChars.push('d');
userRef.update({listOfChars: listOfChars});
I would like to be able to publish simultaneously in two directories of my Firebase database. I created a function for this, according to the example proposed in the "Update specific fields" section of the Firebase Javascript documentation:
function linkTwoUsers(user1, user2) {
// The two users are "connected".
var user1Data = {
userLink: user2
};
var user2Data = {
userLink: user1
};
var updates = {};
updates["/users/" + user1] = user1Data;
updates["/users/" + user2] = user2Data;
return database
.ref()
.update(updates)
.then(() => {
return res.status(200).end();
})
.catch(error => {
return res.status(500).send("Error: " + error.message);
});
}
The problem is that when I run the function, instead of uploading the directories, it replaces all the data present in it.
Here are the user directories before the function:
And then:
How do we make sure the data doesn't overwrite the others? Thank you for your help.
Try to narrow your path to just the property you are trying to update:
updates["/users/" + user1 + "/userLink/"] = user1;
updates["/users/" + user2 + "/userLink/"] = user2;
It seems as though you're creating an entirely new object when you set:
var userData = { someThing: stuff }
When you pass that in, it will override the original object. One way you might solve this (there might be a more efficient way) is to grab the objects from Firebase, add the new property and value to the object, then send the entire object back into Firebase.
In some javascript frameworks, you should be able to use the spread operator to set all of an object's props to another object like this:
var newObject = { ...originalObject }
newObject.userData = "something"
// then save newObject to firebase
I want to send some generated data to the to a specific object child.
var user = firebase.auth().currentUser;
var key = user.uid;
// Set path for created user to be UID
var createProfileRef = firebase.database().ref("profiles/" + key);
var info;
createProfileRef.on("value", function(snapshot) {
var getData = snapshot.val();
info = Object.keys(getData)[0];
});
// Save Plan to logged inn user
var sendData = firebase.database().ref("profiles/" + key + "/" + info + sendDate);
savePlan(sendFat, sendProtein, sendCarbohydrate);
function savePlan(sendFat, sendProtein, sendCarbohydrate) {
var addData = sendData.push();
addData.set({
Macros_Fat: sendFat,
Macros_Protein: sendProtein,
Macros_Carbohydrate: sendCarbohydrate,
});
The only thing I need for this to work is to get the value of the variable "info". I just can't get it to get transferred outside of the function it is declared in...
If I place the function savePlan inside the snapshot it works, but it generated around 1000 keys constantly until I exit the application.
The easiest way you can do that is by setting the variable value in localStorage in the firebase function itself and get it outside the function from localStorage.
Here's the code:
// in firebase function
localStorage.setItem('info',info)
//outside the firebase function
localStorage.getItem('info');
So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});
In my firebase app when a new user signs up I add their initial data like displayname, emai , photourl to the database under the top level users node. This works fine.
Now when a user post a status, I want to upload the the post to top level statuses node where all user statuses are kept. And simultaneously I want to upload the post to current user's posts node i.e users/currentuser/posts.
I am following the methods shown on official firebase site here.
The problem is when I hit the post button nothing happens and no data is posted to the database
My function that gets invoked when the post button is clicked:
function postStatus(){
var ref = firebase.database().ref("allstatuses");
var user = firebase.auth().currentUser;
var newStatusRef = ref.push();
var newStatusKey = newStatusRef.key();
var statusData = {
status: postInput.val(),
likes: 0,
dislikes: 0
};
var updateUserStatus = {};
updateUserStatus["users/" + user.uid + "/" + newStatusKey] = statusData;
updateUserStatus["allstatuses/" + newStatusKey] = statusData;
if(user){
firebase.database().ref().update(updateUserStatus);
}else{
alert("please login");
}
}
What am I doing wrong?
According to the API reference link it is key not key()
Change this
var newStatusKey = newStatusRef.key();
to
var newStatusKey = newStatusRef.key;