admin管理员组

文章数量:1194923

So, I have a problem that can probably be super easily solved I just can't quite figure it out. Essentially at this point, I'm trying to store fields of a specific document into 2 vars so that I can use them elsewhere.

This is my firestore hierarchy:

This is the code I have so far and I think I'm on the right track but I don't know what to replace "//What do I put here" with.

var db = firebase.firestore();
var user = firebase.auth().currentUser;
var usersEmail = user.email;
db.collection("users").where("email", "==", usersEmail)
                    .get()
                    .then(function(querySnapshot) {
                        querySnapshot.forEach(function(doc) {
                            // doc.data() is never undefined for query doc snapshots
                            console.log(doc.id, " => ", doc.data());
                            var firstName = //What do I put here?
                            var lastName = //What do I put here?
                        });
                    })
                    .catch(function(error) {
                        console.log("Error getting documents: ", error);
                    });

So, I have a problem that can probably be super easily solved I just can't quite figure it out. Essentially at this point, I'm trying to store fields of a specific document into 2 vars so that I can use them elsewhere.

This is my firestore hierarchy:

This is the code I have so far and I think I'm on the right track but I don't know what to replace "//What do I put here" with.

var db = firebase.firestore();
var user = firebase.auth().currentUser;
var usersEmail = user.email;
db.collection("users").where("email", "==", usersEmail)
                    .get()
                    .then(function(querySnapshot) {
                        querySnapshot.forEach(function(doc) {
                            // doc.data() is never undefined for query doc snapshots
                            console.log(doc.id, " => ", doc.data());
                            var firstName = //What do I put here?
                            var lastName = //What do I put here?
                        });
                    })
                    .catch(function(error) {
                        console.log("Error getting documents: ", error);
                    });
Share Improve this question edited Sep 23, 2018 at 2:12 JWolfCrafter asked Sep 23, 2018 at 1:07 JWolfCrafterJWolfCrafter 1571 gold badge2 silver badges9 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

doc.data() is just a regular JavaScript object with the contents of the document you just read:

var data = doc.data();
var firstName = data.first;
var lastName = data.last;

Or you can get the field value directly from the DocumentSnapshot:

var firstName = doc.get("first");
var lastName = doc.get("last");

本文标签: javascriptGetting a specific field in a document returned from firebase firestoreStack Overflow