I have been trying to get amount of users that have same "referralId" in my firebase Realtime database,
users {
AY35bkc5cbkufik8gfe3vjbmgr {
email: james #gmail.com
verify: none
referralid: AY35ja35
}
B16fty9jDchfNgdx7Fxnjc5nxf5v {
email: mobilewisdom #gmail.com
verify: none
referralid: AY35ja35
}
}
How can I use JavaScript to count the amount of account with referralid:AY35ja35
I tried:
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
But am getting this error in my console:
Uncaught TypeError: query.get is not a function
In v8/namespaced syntax that'd be:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
const results = await query.get();
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
In v9/modular syntax the equivalent would be:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
const results = await get(query);
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
get(query).then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
Firstly you will have to run a query to get the data from firebase using either firebase package, axios or fetch
Your data is fetched in form of Object containing different objects. You can either user for .. in .. loop to iterate through the object.
var count = 0
for (const user in users) {
if (user.referralid==="AY35ja35") {
count++
}
}
Or use Object.values(object) function to get array of users. Now you can use a JavaScript array function such as map or filter.
by using map. you can do it like this:
var count=0
user.map(user=>{if(user.referralid==="AY35ja35"){count++})
or by using filter
const matchedUsers = user.filter(user=>(user.referralid==="AY35ja35"))
const count = matchedUsers.length
Hope this helps :)
Related
I am also using getStaticprops from next.js.
I am trying to fetch data , I am following the code on firebase documentation, but i keep running into a error
export const getStaticProps = async () => {
const res = await fetch(
"https://jsonplaceholder.typicode.com/photos?_limit=4"
);
const images = await res.json();
console.log(auth.currentUser);
//
const userRef = ref(database, "users/" + auth.currentUser.uid);
onValue(userRef, (snapshot) => {
const properties = snapshot.val();
console.log(properties);
});
//
return {
props: {
images,
properties,
},
};
};
I would like besides add new record , also change 'bill'.
But I don't know what input in this string
const newPostKey = (child(ref(db), )).key;
This action in vuex, that I use for create request to firebase:
async updateInfo({ dispatch, commit, getters }, toUpdate) {
try {
const uid = await dispatch('getUid')
const db = getDatabase();
const updateData = { ...getters.info, ...toUpdate }
const postListRef = ref(db, `/users/${uid}/info`);
const newPostKey = (child(ref(db), ????)).key;
const updates = {};
updates[newPostKey] = updateData;
update(postListRef, updates)
commit('setInfo', updateData)
} catch (e) {
commit('setError', e)
throw e
}
},
Code work up to step const newPostKey..
If I input in this string 'info':
const newPostKey = (child(ref(db), 'info')).key;
Record will be added, but 'info' will be update incorrect:
If you just want to update the value of bill then you can try the following:
const userRef = ref(db, `/users/${uid}/info`);
update(userRef, { bill: 100 }).then(() => { // <-- replace 100 with your bill amount
console.log("Bill Amount Updated")
}).catch(e => console.log(e))
If you want to increment the bill by a certain amount, you can do so using increment() function.
update(userRef, { bill: increment(100) }) // increment by 100
How to set a specific quarry for a sub collection when using a snapshot ?
I am tring to sort sub collection resutls by createdAt with the limit of last 5
useEffect(() => {
//const querydata = query(docRefComm, orderBy('createdAt'), limit(5));
let collectionRef = collection(db, 'Comm', docId, 'messages');
const unsub = onSnapshot(collectionRef , (doc) => {
doc.forEach((el) => {
console.log(el.data());
});
});
return () => {
unsub();
};
}
}, []);
You can build a query() using CollectionReference as shown below:
let collectionRef = collection(db, 'Comm', docId, 'messages');
const q = query(collectionRef, orderBy('createdAt'), limit(5))
const unsub = onSnapshot(q , (qSnap) => {
})
Checkout Listen to multiple documents in a collection in the documentation.
I tried to implement the followers/following function and it succeeds but, I have a problem retrieving followers and following lists from real-time firebase.
When the user presses on another username followers/following, it sends the uid of the pressed user to this class, then by using the uid followers' list is retrieved and displayed.
The uid is correct at the beginning of the class, but the followers' list returns undefined and sometimes it returns a list on the second save(when I press Ctrl+s).
export default function showFollowers({
navigation,
route
}) {
const [followerslist, setFollowersList] = useState();
const [uid, setuid] = useState(route.params.uid);
const [usersList, setUsersList] = useState([]);
const followersl = [];
// ---snip---
}
HERE, the followers list returned undefined.
useEffect(
() => {
const usersRef1 = firebase.database()
.ref('users/' + uid)
.child("followers");
usersRef1.on('value', async (snapshot) => {
const users1 = snapshot.val();
//const followersl= [];
for (let id in users1) {
followersl.push(users1[id]);
}
await setFollowersList(followersl)
console.log(followerslist) // undefined
console.log(uid) // correct
});
},
[]
);
// Calling second to return info of each follower [profile image,username,name] to be displayed as flat list.
second;
const second = () => {
for (var i = 0; i < followerslist.length; i++) {
getInfo(followerslist[i]);
}
}
const getInfo = (element) => {
const usersRef = firebase.database()
.ref('users')
.orderByChild('usernameLC')
.equalTo(element.toString().toLowerCase());
usersRef.on('value', (snapshot) => {
const users = snapshot.val();
for (let id in users) {
usersList.push(users[id]);
}
setUsersList(usersList);
});
}
I have a cloud function that "Joins" data from a list of documents in a collection.
I then return the result as an array, but I want to return the documentId as well (doc.id) in the list that i return.
How can i do that?
const restData = [];
//const userId = ctx.auth.uid;
const userId = 'dHAP1CNN6LhJWddQoTqyIkqIjhB2'; // !!! TEST ONLY
const all = await db.collection(`/customers/${userId}/lunch_cards`).listDocuments().then((snapshot) => {
snapshot.forEach(doc => {
const nextData = db.collection(`/restaurants`).doc(doc.id).get();
const newData = {...nextData, documentId: doc.id}; <-- This does not work only documentId isout in newData
console.log(util.inspect(newData));
restData.push(nextData);
console.log(doc.id);
});
});
const snaps = await Promise.all(restData);
const responseArray = snaps.map((s) => {return s.data()});
return responseArray;
I solved it!
Solution:
Just adding a new string to the array :)
const responseArray = snaps.map((s) => {
const snapData = s.data();
if (snapData) {
snapData['id'] = s.id;
}
return snapData;
});