What does .where.get() return? - javascript

i am new this website and to mobile programming.
My questions is:
In firebase i have a collection path with some documents.
.collection(maybe).doc(random)
Each doc has subcollection as well.
Also each doc has data such as:
roomName: randomName
roomPassword: randomPass.
So, now i would like to use the query with .where operator and .get like this:
const docRef=db.collection(‘maybe’)
docRef.where(‘roomName’ ‘==‘ ‘randomName’).get()
My question is what do i get back? As i understand i get the querySnapshot, but i do not fully get how to get the second field in data specifically i.e. how to get roomPass?

const docRef = db.collection(‘maybe’);
const futureSnapshot = docRef.where(‘roomName’,‘==‘,‘randomName’).get();
gives you a promise of snapshot.
You have to "await".
const docRef = db.collection(‘maybe’);
const snapshot = await docRef.where(‘roomName’,‘==‘,‘randomName’).get();
after that you can get your data :
const room = snapshot.data(); // undefined if your query has no results
This link could help you
Happy coding !
EDIT
If your document looks like this :
{
randomName: "a name",
randomPassword: "a password"
}
Then you get your data like that :
const room = snapshot.data(); // undefined if your query has no results
const { randomPassword } = room;

Related

Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>)

Description of the problem:
My App aim is to store family spending in Firebase Realtime Database. I want that, when a new spending is stored, a notification is sent to all other devices.
I try to send a notification to a single device and it works fine, but when I try to get all the tokens in an array, I have an error:
TypeError: Cannot convert undefined or null to object at Function.keys ().
code of index.js :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.androidPushNotification = functions.database
.ref("{nodo}/spese/{spesaPush}")
.onCreate(async (snapshot, context) => {
const original = snapshot.val();
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/{tutti}/token`).once('value');
let tokensSnapshot;
let tokens;
tokensSnapshot = await getDeviceTokensPromise;
// This is the line generating the errors.
// If I get only a specific token and
// use tokens = tokensSnapshot.val(); anything works fine
tokens = Object.keys(tokensSnapshot.val());
const result = original.chi + " ha speso " +
original.costo + " € per acquistare " +
original.desc;
console.log(result);
const payload = {
notification: {
title: 'New spending inserted!',
body: result,
}
};
const response = await admin.messaging().sendToDevice(tokens, payload);
return result;
});
It seems that values are not reached yet, but I thought that the keyword await lets system to wait until all data are available. From the log I noticed that the value I need is null and I don't understand why.
If I use this line of code:
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/SpecificUser/token`).once('value');
....
//then
tokens = tokensSnapshot.val();
The notification is sent to the device that has the token under the name of "SpecificUser"
EDIT:
I provide a pic of my db. I notice that none of the field is null, so I don't know why I see this error
Thank you to anyone that helps me
i had same error and it is solve by database...
when i saw my database values unfortunately i stored undefined value so my whole result got error like you...
see your whole values and fields that store values properly.

Firestore: Unable to fetch document from query - doc.data is not a function

here usersList contains the list of username of people and androidNotificationToken is the field in the document of the user which contains the token for sending the notification.
const registrationTokens=[];
const indexOfSender=usersList.indexOf(senderUsername); // to remove the name of person sending message
let removedUsername=usersList.splice(indexOfSender,1);
usersList.forEach(async(element)=>{
const userRef = admin.firestore().collection('users').where("username","==",element);
const doc = await userRef.get();
registrationTokens.push(doc.data().androidNotificationToken);
});
The error on running the cloud computing am receiving is :-
TypeError: doc.data is not a function
at usersList.forEach (/workspace/index.js:191:37)
at process._tickCallback (internal/process/next_tick.js:68:7)
userRef.get() is going to return a QuerySnapshot (not a DocumentSnapshot) object that can contain 0 or more documents matched from the query. Use the API provided by QuerySnapshot to find the resulting documents, even if you are expecting only one document.
If you are expecting just one document from the query, you should at least verify that you got one before indexing into the result set.
const query = admin.firestore().collection('users').where("username","==",element);
const qsnapshot = await query.get();
if (qsnapshot.docs.length > 0) {
const doc = qsnapshot.docs[0];
const data = doc.data();
}
else {
// decide what you want to do if the query returns nothing
}

How to query for objects with a certain property in a Firestore collection, Firebase

I am trying to query for objects in firestore collection with a certain property, my Firestore DB looks as shown in the below picture.
The below code does not work as I am interested in querying for objects based on the the property inside an object. In this case I want all the cases (objects) with "status"=="treated" Is there a way to do it ?
const db = firebase.firestore();
const casesRef = db.collection("mgm/hospital/cases");
// Create a query against the collection.
var query = casesRef.where("status", "==", "active").limit(25);
const queryRef = query.get();
queryRef.then(function(documentSnapshots) {
const cases = documentSnapshots.docs.map((doc) => doc.data());
console.log(cases);
});
Since the field patientDetails is a map, the following should do the trick:
var query = casesRef.where("patientDetails.status", "==", "active").limit(25);

firebase cloud functions return nested documents

I'm using firestore database and I am trying to retrieve data from a collection, but the data is related to another document in another collection.
What I'm trying to do is the following:
exports.acc = functions.https.onRequest(async (req, res) => {
let docRef = admin.firestore().collection('LoggedIn').doc('CurrentLogin');
snapshot = await docRef.get();
doc = snapshot.data();
usr = doc["Email"];
// I want to get the Level from the Current Logged In user (the 'usr' below)
let docRef1 = admin.firestore().collection('Accounts').doc(usr);
snapshot1 = await docRef1.get();
doc1 = snapshot1.data();
usr1 = doc1["Level"];
return res.send(usr1);
});
I've spent the last day just trying and trying with no luck, if I do one document it works, for example when I do this:
exports.acc = functions.https.onRequest(async (req, res) => {
let docRef = admin.firestore().collection('LoggedIn').doc('CurrentLogin');
snapshot = await docRef.get();
doc = snapshot.data();
usr = doc["Email"];
return res.send(usr);
});
It really returns the email address for the current logged in user.
why is the code above not working? what am I doing wrong ?
Any help is greatly appreciated
Thank you :)
I fixed the problem, turns out it was because the 'Level' is an integer value, so I had to add toString(), like that:
usr1 = doc1["Level"].toString();

How to find out if a record exists in Firestore (node)

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.

Categories

Resources