Using Firebase, I am trying to display a user's profile information based on their user id. I can currently save data to the database under the users ID.
I am able to display the general information from hobbies, but when altering the variables to display the user's data the id is then null or uid undefined and i can't figure out why? The user is signed in, and can upload data using their id.
//Display Profile Information
(function(){
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
const preObject = document.getElementById('object');
const list = document.getElementById('list');
//Displays Hobbies correctly, When changing 'object' & 'hobbies'
//to 'Users' & uid nothing is shown.
const dbRefObject = firebase.database().ref().child('object');
const dbRefList = dbRefObject.child('hobbies');
dbRefObject.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
dbRefList.on('child_added', snap => console.log(snap.val()));
};
Alterations:
const dbRefObject = firebase.database().ref().child('Users');
const dbRefList = dbRefObject.child(uid);
I am extremely grateful for any help or advice!
It looks like you are getting a value for dbRefObject which is pointed to the entire Users object and not a specific user's UID.
Try changing this:
dbRefObject.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
to this (dbRefObject changes to dbRefList):
dbRefList.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
Related
i've been working on an app(Node.js with MongoDB using mongoose), and the server connects to 2 different databases, 1 generic containing username and password pairs for user authentication. Then, when the user signs in, I want to connect to a different database, named after the user's userId. I managed to create a module for sharing the generic UA database, but it's more difficult with the second one, since it doesn't open with the connection, but later on, when the user signs in. I guess i got inspired by the idea of react context kind of sharing.
So far i've got something like this
const mongoose = require("mongoose");
/*
UA = User Authentication
US = User Specific
DB = DataBase
*/
const UA_DB = mongoose.createConnection(/*...*/);
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB, Order, Item, Ingredient, Place;
console.log("opened UA database");
function sendUserId(newUserId) {
userId = newUserId;
US_DB = mongoose.createConnection(/*... ${newUserId} ...*/ );
Order = US_DB.model("Order", require("../../data-schemas/order"));
Item = US_DB.model("Item", require("../../data-schemas/item"));
Ingredient = US_DB.model(
"Ingredient",
require("../../data-schemas/ingredient")
);
Place = US_DB.model("Place", require("../../data-schemas/place"));
console.log("opened US database");
}
module.exports = {
UA_DB: {
User,
},
US_DB: {
Order,
Item,
Ingredient,
Place,
},
sendUserId,
};
Now, if I hadn't made it clear, the first, UA_DB works just fine, the user signs in just fine... When it comes to the US_DB i always get undefined as values(Cannot read property 'find' of undefined). I suspect the problem could be, that the exported value doesn't update with the value of the variables. Any ideas, how this could be solved?
Well, i figured it out. Instead of using precise values I use a function to return them, and to connect to the database.UserId is stored in a token, so after verification i check whether i am already connected to the right database (with the userId variable, which stores previous values) and then return curretn values of the models now my code looks something like this
const mongoose = require("mongoose");
/*
UA = User Authentication
US = User Specific
DB = DataBase
*/
const UA_DB = mongoose.createConnection(/* ... */
);
const User = UA_DB.model("User", require("../../data-schemas/user"));
let US_DB,
Order,
Item,
Ingredient,
Place = "some default value";
console.log("opened UA database");
let userId = "";
function getUS_DBModels(newUserId) {
if (newUserId !== userId) {
userId = newUserId;
US_DB = mongoose.createConnection(`...${userId}...`
);
Order = US_DB.model("Order", require("../../data-schemas/order"));
Item = US_DB.model("Item", require("../../data-schemas/item"));
console.log("opened a US_DB connection");
Ingredient = US_DB.model(
"Ingredient",
require("../../data-schemas/ingredient")
);
Place = US_DB.model("Place", require("../../data-schemas/place"));
}
return {
Order, Item, Ingredient, Place
}
}
module.exports = {
UA_DB: {
User,
},
getUS_DBModels,
};
For anyone wondering, in different modules you can access the values like this
const dbHandler = require("./path/to/the/module");
const { Item } = dbHandler.getUS_DBModels("UserId");
I'm working on restaurant website (client-side project) and facing this problem, I want to make an admin page will show me all the orders placed by the customers and the way I choose that to save the order details in local storage then save it in this indexedDB then display the (the orders) at the admin page so I made this code and it work all good I guess to save the order and all customer details
document.getElementById('submittheorder').onclick = function() {
let i = 0;
const versionDB = 1;
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open("CustomersOrders", versionDB);
open.onupgradeneeded = function() {
let db = open.result;
let store = db.createObjectStore("OrdersTable", {
keyPath: "id"
});
let index = store.createIndex("CIndex", ["FullName", "Order", "House", "Road", "Block"]);
};
open.onsuccess = function() {
let db = open.result;
let tx = db.transaction("OrdersTable", "readwrite");
let store = tx.objectStore("OrdersTable");
let index = store.index("CIndex");
store.put({
FullName: (sessionStorage.getItem("Cfullname")),
Order: (sessionStorage.getItem("order")),
House: (sessionStorage.getItem("CHouse")),
Road: (sessionStorage.getItem("CRoad")),
Block: (sessionStorage.getItem("CBlock"))
});
tx.oncomplete = function() {
db.close();
location.href = "Thanks.html";
};
}
}
Now the problem is I want to retrieve all the orders and the details for each object to the admin page
the second problem is that i want to check if the database already exist then insert new object not make a new database and save only one object, in a nutshell i want only one database to make and next times save the orders at that database.
Thank you :)
You can place this logic in the function that handles an upgrade event. There are essentially two ways. You can check if object stores and indices exist, using for example db.objectStoreNames.contains(), or you can compare versions by accessing the version properties from the database object or the event object.
For example, you would want to only create an object store if it did not already exist. If it does not already exists, then you know this is when your database is created.
Something that was so easy in firebase database, impossible for me to accomplish in firestore. I just need to know if a record exists in a specified document.
const user = firebase.auth().currentUser.uid;
const currentPostId = this.posts[index].id;
const ref = db.collection(`likes`).doc(`${currentPostId}`); // need to know if this doc has records
The post has a store of records with just the userids that have liked the post, and a timestamp.
So far I'm able to do this:
const ref = db.collection(`likes`).doc(`${currentPostId}`);
ref
.get()
.then(snapshot => {
console.log("Exists?" + snapshot.exists); //true
})
But for the life of me I just CANNOT find a way to go one level deeper.
const ref = db.collection(`likes`).doc(`${currentPostId}/${user}`); //invalid reference segments must be odd numbers
const ref = db.collection(`likes`).doc(currentPostId).collection(user) //undefined
I've spent tthree days trying different ways. in firebase database it was just:
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var a = snapshot.exists(); // true
var b = snapshot.child("name").exists(); // true
var c = snapshot.child("name/first").exists(); // true
var d = snapshot.child("name/middle").exists(); // false
});
You can read the document and check whether the document has a field with the user id.
const ref = db.collection(`likes`).doc(currentPostId);
ref
.get()
.then(doc => {
console.log("Exists?" + doc.exists); //true
if(doc.exists){
var documentData = doc.data();
// Check whether documentData contains the user id
if (documentData.hasOwnProperty(userId)) {
// do something
}
}
})
The code above is not tested but it should work.
A hint! You can and should store timestamps, which are generated on the client side with the firestore server timestamp:
admin.firestore.FieldValue.serverTimestamp();
Because, if the client have changed the local time you could get a wrong time.
I am able to retrieve the child if it is present as data/ a, data/b. But I want to retrieve all the data which are present as data/key1/a, data/key1/b, data/key2/a, data/key2/b.
Now I am using the code as,
var rootRef = firebase.database().ref().child("notifications");
rootRef.on("child_added", snap => {
var uid = snap.child("uid").val();
});
This is giving me the data present in - notifications/key1/uid, notifications/key2/uid.
My database is made as notifications/key1/key1timestamp/uid, notifications/key2/key2timestamp/uid.
How do I edit my code to access that?
Try the following:
var db = firebase.database();
var ref1 = db.ref("notifications");
ref1.on("value", (snapshot) => {
snapshot.forEach((childSnapshot)=> {
childSnapshot.forEach((childrenSnapshot)=>{
let userId = childrenSnapshot.val().uid;
});
});
Assuming you have this database:
notifications
key1
key1timestamp
uid: id_here
key2
key2timestamp
uid:id_here
Since the snapshot is at notifications then loop twice to be able to retrieve the nested children
I was able to save the displayName to the user in Firebase, but I am not sure how to display that name on the page in JS.
Currently, I am using this:
document.getElementById('txtName').innerHTML = firebase.auth().currentUser.displayName;
Check if your element is correctly identified and display it to the console.
console.log(document.getElementById('txtName'));
The Firebase syntax is ok, just check the user against null, like:
var user = firebase.auth().currentUser;
var name, output;
output = document.getElementById("txtName");
if (user != null) {
name = user.displayName;
output.innerHTML= name;
}