Reputation: 3
I'm trying to get Hello World working here -- just get my Node script to talk to Firebase. I made a script I think should read the "stories" collection, but I get no response from Firebase. I'm sure I'm missing something incredibly basic. Please help!
var db = admin.database();
var ref = db.ref("stories");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
console.log('exiting');
...but what I get is:
p:0: Browser went online.
p:0: Listen called for /stories default
exiting
p:0: Making a connection attempt
p:0: Auth token refreshed
getToken() completed. Creating connection.
c:0:0: Connection created
c:0:0:0 Websocket connecting to wss://*****.firebaseio.com/.ws?v=5
I kludged on a way to wait longer, and got this:
p:0: Browser went online.
p:0: Listen called for /stories default
exiting
p:0: Making a connection attempt
p:0: Auth token refreshed
getToken() completed. Creating connection.
c:0:0: Connection created
c:0:0:0 Websocket connecting to wss://*****.firebaseio.com/.ws?v=5
c:0:0: Closing unhealthy connection after timeout.
c:0:0: Closing realtime connection.
c:0:0: Shutting down all connections
c:0:0:0 WebSocket is being closed
p:0: data client disconnected
p:0: Trying to reconnect in 0ms
0: onDisconnectEvents
p:0: Making a connection attempt
getToken() completed. Creating connection.
c:0:1: Connection created
c:0:1:0 Websocket connecting to wss://*****.firebaseio.com/.ws?v=5
c:0:0:0 Websocket connection was disconnected.
What am I doing wrong?
Upvotes: 0
Views: 394
Reputation: 326
you talked about collection
, so I think you're working on Cloud Firestore, not Realtime Database.
So the code should be:
const db = admin.firestore();
db.collection('stories').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
Please have a look this image: enter image description here
Upvotes: 1
Reputation: 317372
Tru once()
instead of on()
. once()
just queries a single time and returns a promise. on()
establishes a listener that run until you remove it, and it doesn't return a promise.
ref.once('value')
.then(snapshot => {
console.log(snapshot.val());
})
.catch(error => {
console.error(error);
});
Upvotes: 0