Reputation: 151
I am new to js and firestore (and the whole firebase eco-system)
I want to query data with 2 where fields (account_id, device_id) but I always get "No document found"
let selectQuery = admin.firestore().collection("devices");
selectQuery.where("account_id", "==", context.auth.uid);
selectQuery.where("device_id", "==", deviceId);
selectQuery.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
return "asd";
}).catch(function(error) {
console.log("Error getting document:", error);
});
I even tried removing the where clauses however the data still cannot be found but it's there:
The parameter from context and data are // UID = UIDwFK2JVghw8XjVGqlEE0Uj09irGK2 // DEVICE_ID = 552cbe50f935de7a
As request here is the full code:
exports.authDevice = functions.https.onCall((data, context) => {
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
const deviceName = data.device_name;
const deviceId = data.device_id;
const isQR = data.is_qr;
const uid = context.auth.uid;
console.log("DEVICE NAME: " + deviceName);
console.log("DEVICE ID: " + deviceId);
console.log("is QR: " + isQR);
console.log("UID: " + uid);
admin.firestore().collection("devices")
.where("account_id", "==", context.auth.uid)
.where("device_id", "==", deviceId)
.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
return "asd";
}).catch(function(error) {
console.log("Error getting document:", error);
});
});
Upvotes: 1
Views: 1026
Reputation: 151
After some debuging I found that it does not return a single document but a "QUERY SNAPSHOT" which has method empty or size.
After the change:
return admin.firestore().collection("devices").where("account_id", "==", context.auth.uid)
.where("device_id", "==", deviceId).get().then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
console.log("Empty: " + snapshot.empty);
console.log("Size: " + snapshot.size);
return "asd"
})
.catch((err) => {
console.log('Error getting documents', err);
});
Upvotes: 3
Reputation: 598728
The context.auth
is only available for realtime database triggered functions. From the documentation for the EventContext.auth
parameter:
Authentication information for the user that triggered the function. This object contains uid and token properties for authenticated users. For more detail including token keys, see the security rules reference.
For an unauthenticated user, this field is
null
. For event types that do not provide user information (all except Realtime Database) or for Firebase admin users, this field will not exist.
Upvotes: 1