Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - I can get all documents but unable to retrieve single document in Firestore

EDIT:

Rookie error, I was trying to reference a document by ID but the input I was using had space at the end due to human error.

const id = "kahgsdjhagsd " // should be "kahgsdjhagsd"
const usersRef = fb.db.collection('users').doc(id);

========

I am trying to retrieve a single document yet it indicates it does not exist, despite the fact when I run the logic to get ALL documents it is in the response

    const users = await db.collection('users').get();
    users.forEach(user => {
        console.log(user.id, user.data()) // <-- Works! displays ID...
        const userRef = db.collection('users').doc(user.id)
        if (userRef.exists) {
            console.log("User exists")
        } else {
            console.log("User does not exist") // <-- Getting this though
        }
    })

Its very weird, the below works if I hardcode the ID as a string:

async getUser() {
    const id = "some-id-to-a-document"
    const usersRef = fb.db.collection('users').doc(id);
    const doc = await usersRef.get();
    if (!doc.exists) {
        console.log('No such document!'); 
    } else {
        console.log('Document data:', doc.data()); // <-- Getting this...
    }
}

But if I try to input an ID via the function...

async getUser(id) {
    console.log(id) // <-- shows the ID!
    const usersRef = fb.db.collection('users').doc(id);
    const doc = await usersRef.get();
    if (!doc.exists) {
        console.log('No such document!'); // <-- Getting this...
    } else {
        console.log('Document data:', doc.data());
    }
}
question from:https://stackoverflow.com/questions/65866556/i-can-get-all-documents-but-unable-to-retrieve-single-document-in-firestore

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

const userRef = fb.usersCollection.doc(user.id)

In the above line, You have to get the DocumentSnapshot using get() before checking the document existence.

const userSnap = await fb.usersCollection.doc(user.id).get();
if (userSnap.exists) {
    console.log("User exists")
} else {
    console.log("User does not exist")
}

And another important note, within forEach using async / await is not preferable as it won't give expected result always. The traditional for..loop would be good to get the work done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...