0

after not finding anything online, I decided to write here. I need to get all the document in the /user/uid collection in Node JS. When I use the Firebase code it replies like this:

Promise {<pending>}

Please help me!

PS: I don't want to use Firebase Admin SDK and await.

"Full" code

var express = require('express');

const { initializeApp } = require("firebase/app");
const { getDatabase, ref, get, child, set, onValue} = require("firebase/database");
const { getFirestore, collection, getDoc, doc} = require("firebase/firestore");

const firebaseApp = initializeApp(firebaseConfig);

// Get a reference to the database service

var app = express();

const PORT = process.env.PORT || 5050

app.get('/', (req, res) => {
    res.send('This is my demo project')
});

const db = getDatabase();
const firestore = getFirestore();


const document = getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"));
  
console.log(document);

//Response: "Promise {<pending>}""

1 Answer 1

1

Firebase method calls are asynchronous. So for both the Admin SDK or the JS SDK you have to deal with the asynchronicity, either by using then or by using async/await.

If you receive Promise {<pending>} it is because the asynchronous method getDoc returns a Promise and this promise is not fulfilled, but is still pending.

So you need to dive into the documentation on how to use Promises... or the async/await keywords.

In your case, the following will do the trick:

getDoc(doc(collection(firestore, 'users'), "BW5kylV6rtZXtYibpKGc2m1asRm1"))
.then(snap => {
   console.log(snap.data())
})

However, if you write this code for running on a Node server you own, I would recommend to use the Admin SDK.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the prompt reply! The code you gave me works. I wanted to ask you one last thing, why do you advise me to use the Admin SDK, keeping the credentials is no less secure? I have to perform mostly read-only operations on Firestore and Realtime DB. Thanks so much
Glad that I could help you. To answer your question I have myself a question: You mention that you use Node.js. Where does your code run? On a server you own?
I need to build APIs that take the values from the database. For now I hosto it locally.
Ok, so you could also use one or more Cloud Functions. In any case, whether you use your own server or a Cloud Fucntion, the recommended SDK in this case is the Admin SDK. See here for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.