I have been trying to add data to my database without any luck.
In my code i have made a button when click, it will add data to my users database but it will not add it to the user but it just add the data outside like this:
is it because you cant add data when you have use the createUserWithEmailAndPassword() function?
Can anyone please show me how it is done?
btn.addEventListener("click", function()
{
firebase.auth().onAuthStateChanged(function(user)
{
if (user)
{
var massage = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.push(data);
}
});
});
Whenever you call push() Firebase generates a new unique ID. So to add the new data to the existing node, you should not call push. Instead you need to find a reference to the existing node for that user.
The easiest (and by far most common) way to do this, is to store the user data under the UID of each user.
Users
kHD...NoS
username: "bob"
Also note that there's no reason to put this type of onAuthStateChange listener inside a button click handler. Just attach it from the top-level JavaScript and it will trigger whenever the user signs in or when their auth state changes in any other way.
Alternatively, if the code really must run in response to the button click, there's no real use for a auth state listener and you can just check firebase.auth().currentUser:
btn.addEventListener("click", function()
{
if (firebase.auth().currentUser)
{
var message = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.child(firebase.auth().currentUser.uid).update(data);
}
}
Your code seems correct if you want to insert a new entry in Firebase database (just like your screenshot shows).
But, if you really want to sign up a new user, then you should be using firebase.auth().createUserWithEmailAndPassword() instead.
Finally, if you really want to update an existing node, see Frank response above ;-)
try this. you can change update to set. In your case something like
demo.update("users/KIK...fuA","display","my message");
//REVEALED METHOD TO ADD NODES WITH DATA TO REALTIME DATABASE
//eg, demo.update('mynode','myKey','myValue')
var demo = (function() {
var pub = {};
pub.update = function (node,key,value){
var ref = firebase.database().ref('/');
var obj = {};
obj[key] = value;
ref.child(node).update(obj)
.then(function() {
console.log('Update Ran Successfully');
});
}
//API
return pub;
}());
Related
I have an electron app with a form that will be used to get some information. I don't have an external server or url where I can sent the data, I need to get the form data and store them using dexie.js and vue that I'm using to intercept the click event on submit button. I'm not sure how I can save data, this because I need to get values from the form and then call dexie to store them, I'm using a vue method to manage the click, I was using the document.forms to get form elements name and value, but this is a bad approach. can anyone help me to find a way to achieve this?
//import Dexie from 'dexie';
const Dexie = require('dexie');
// Force debug mode to get async stacks from exceptions.
Dexie.debug = true; // In production, set to false to increase performance a little.
let db = new Dexie('clients');
db.version(1).stores({
websites: "++id,client_name,hosting_provider,website_domain,panel_user,panel_pwd,db_host,db_name,db_user,db_pwd,wp_user,wp_pwd"
});
$(document).ready(function(){
var myapp = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
saveData(){
//var form = document.getElementById('client-info') //document.forms;;
var form = $('#client-info').serialize();
console.log(form);
//var formData = new FormData(form);
//console.log(formData);
// $.each( form[0].elements, function(i, index){
// console.log( index );
// console.log( form[0].elements[i].name, form[0].elements[i].value );
// // or make a new one
// db.clients.add({
// form[0].elements[i].name: form[0].elements[i].value
// });
// });
//console.log(Dexie);
//console.log(db);
}
}
});
console.log(myapp);
});
NB: for now I've commented the code because it will not work, it don't save the data.
You might want to try adding the Dexie code to the main process, which acts as the backend in traditional web terms, and send the form via ipcRenderer to the main process (similar to what I proposed over here.
I am trying to get a way to delete firestore document by a click event.
here is what i have so far. x is the document id i get from firestore. But how to get the ID change dynamically based on the content show in the page? SO that user can delete the content they wanted.
var deleteContent = document.getElementById('delete');
deleteContent.addEventListener('click', function(e) {
// get current document ID
x = 'poOjcQce2iiKzp2FaFVA'
var getId = db.collection("checkin").doc(x);
getId.delete().then(function() {
console.log(" successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
});
Thanks
Firebase Cloud Firestore allows you to perform simple and compounded queries. Essentially, you can provide a condition in the db.collection(<COLLECTION>).where() clause which will filter all documents that match that certain condition.
For illustrative purposes, suppose documents in the a collection follow the following structure: { id, '123', name: 'test', color: 'red' }. If you want to get all documents with the color red, you can simply call db.collection('a').where('color', '==', 'red'), which you can then iterate into to process each document that matches that condition.
Moreover, in your specific case, suppose your document structure is { id, content }you can try something like this:
var deleteContent = document.getElementById('delete');
deleteContent.addEventListener('click', function(e) {
// get current document ID
let docToDelete = db.collection("checkin").where('content', '==', 'CONTENT_GOES_HERE')
x = docToDelete.id;
var getId = db.collection("checkin").doc(x);
getId.delete().then(function() {
console.log(" successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
});
However, a much simpler way would be to store the document id somewhere within your application whenever a specific document is read, local storage or session storage for instance. As such, you can refer to the document id whenever you need. For example, suppose that you fetch all of a user's documents in an onLoad event handler --- suppose that you have HTML elements with the id 'content1', 'content2', 'content3', etc. and that it is where the contents of your documents are shown. You can try something like this:
let userId = 123;
[...].onload = () => {
// Get all of the documents belonging to this user
let i = 0;
let docs = [];
let documents = db.collection('posts').where('userId', '==', userId);
documents.forEach(doc => {
document.getElementById(`content${i}`).innerHTML = JSON.stringify(doc.data()); // Just stringifying to be certain
/**
* Extra step to add the document id in the sessionStorage so that we can refer to it later
*/
htmlId = 'content' + i;
sessionStorage.setItem(htmlID, doc.id );
})
}
In doing so, you can simply refer to the document id like such sessionStorage.getItem('content2').
Note that in any of the examples I listed, there is heavy preparation that needs to be done in order for this to be as smooth sailing as possible. However, wouldn't you agree that a programmer merely is a person that spends hours on things that takes minutes for the sake of making it easier in subsequent uses? :)
I have my database in firebase as you can see here https://snag.gy/bhopOk.jpg
The user scans a product and brings you the number of this product, which is put in an input, then when you click on search you must bring the description and the value of that item and show it somewhere in the front
This is my frontend
How would the function or query be so that when the person click on search brings me the requested data? I know it's a simple query but I do not have it very clear I'm new to ionic
I tried to do this to see if I returned something in the console but nothing
findproduct(){
var ref = firebase.database().ref("/productos/");
ref.orderByChild("Producto").equalTo(1706).on("child_added", function(snapshot) {
console.log(snapshot.key);
});
}
You can write your function as follows. However, note that query.once() is asynchronous and returns a Promise. So you have to take that into account when you call it.
findproduct(productID) {
var query = firebase.database().ref("productos").orderByChild("Producto").equalTo(productID);
query.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
});
});
}
When you just want to query once, use the once() method: it "Listens for exactly one event of the specified event type ('alue' in this case), and then stops listening". See the documentation here.
When using the on() method, you are constantly listening to data changes at the location defined by the query. See the doc here.
I have an app that uses firebase, the whole stack pretty much, functions, database, storage, auth, messaging, the whole 9. I want to keep the client end very lightweight. So if a user comments on a post and "tags" another user, let's say using the typical "#username" style tagging, I moved all of the heavy lifting to the firebase functions. That way the client doesn't have to figure out the user ID based on the username, and do everything else. It is setup using triggers, so when the above scenario happens I write to a "table" called "create_notifications" with some data like
{
type: "comment",
post_id: postID,
from: user.getUid(),
comment_id: newCommentKey,
to: taggedUser
}
Where the taggedUser is the username, the postID is the active post, the newCommentKey is retrieved from .push() on the comments db reference, and the user.getUid() is from the firebase auth class.
Now in my firebase functions I have a "onWrite" trigger for that specific table that gets all of the relevant information and sends out a notification to the poster of the post with all the relevant details. All of that is complete, what I am trying to figure out is... how do I delete the incoming event, that way I don't need any sort of cron jobs to clear out this table. I can just grab the event, do my needed calculations and data gathering, send the message, then delete the incoming event so it never even really exists in the database except for the small amount of time it took to gather the data.
A simplified sample of the firebase functions trigger is...
exports.createNotification = functions.database.ref("/create_notifications/{notification_id}").onWrite(event => {
const from = event.data.val().from;
const toName = event.data.val().to;
const notificationType = event.data.val().type;
const post_id = event.data.val().post_id;
var comment_id, commentReference;
if(notificationType == "comment") {
comment_id = event.data.val().comment_id;
}
const toUser = admin.database().ref(`users`).orderByChild("username").equalTo(toName).once('value');
const fromUser = admin.database().ref(`/users/${from}`).once('value');
const referencePost = admin.database().ref(`posts/${post_id}`).once('value');
return Promise.all([toUser, fromUser, referencePost]).then(results => {
const toUserRef = results[0];
const fromUserRef = results[1];
const postRef = results[2];
var newNotification = {
type: notificationType,
post_id: post_id,
from: from,
sent: false,
create_on: Date.now()
}
if(notificationType == "comment") {
newNotification.comment_id = comment_id;
}
return admin.database().ref(`/user_notifications/${toUserRef.key}`).push().set(newNotification).then(() => {
//NEED TO DELETE THE INCOMING "event" HERE TO KEEP DB CLEAN
});
})
}
So in that function in the final "return" of it, after it writes the finalized data to the "/user_notifications" table, I need to delete the event that started the whole thing. Does anyone know how to do that? Thank you.
First off, use .onCreate instead of .onWrite. You only need to read each child when they are first written, so this will avoid undesirable side effects. See the documentation here for more information on the available triggers.
event.data.ref() holds the reference where the event occurred. You can call remove() on the reference to delete it:
return event.data.ref().remove()
The simplest way to achieve this is through calling the remove() function offered by the admin sdk,
you could get the reference to the notification_id through the event, i.e event.params.notification_id then remove it when need be with admin.database().ref('pass in the path').remove(); and you are good to go.
For newer versions of Firebase, use:
return change.after.ref.remove()
I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('user')).name);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!
I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:
function getNextUnique () {
var next = localStorage.getItem('nextUniqueId');
next = next ? parseInt(next) : 0;
var newNext = next + 1;
localStorage.setItem('nextUniqueId', newNext);
return next;
}
Call it whenever you want to save a new user:
localStorage.setItem(getNextUnique(), JSON.stringify(user));
It makes more sense to use the user's email. Simplicity is good.
BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?
If so, then this is fine. But i wonder if you are really thinking about how localStorage works...