问题
I can request a specific document in a collection successfully. But I need to be able to query all documents, as Firestore (unlike the realtime database) doesn't support exporting.
I know the following is not possible, but surely there is some way to export a whole collection?
router.get('/firebase', function (req, res) {
var admin = require('firebase-admin');
const firebaseConfig = require('../firebaseConfig.json');
admin.initializeApp({
credential: admin.credential.cert(firebaseConfig),
databaseURL: 'https://***.firebaseio.com'
});
let db = admin.firestore();
let cityRef = db.collection('marketing').doc('*');
let getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
});
回答1:
A refactored version of this answer by Doug Stevenson
router.get('/firebase', async function (req, res) {
var admin = require('firebase-admin');
const firebaseConfig = require('../firebaseConfig.json');
admin.initializeApp({
credential: admin.credential.cert(firebaseConfig),
databaseURL: 'https://gundies.firebaseio.com'
});
let db = admin.firestore();
const snapshot = await db.collection("marketing").get();
const docs = snapshot.docs.map(doc => doc.data())
The variable 'docs' will hold all your data!
回答2:
db.collection('marketing').doc('*') is not the correct syntax. There are no document wildcards in Firestore queries. Just use db.collection('marketing').get() to get a QuerySnapshot with all the documents in the collection.
It works just like you see in the documentation for queries, except you are not specifying any filter to limit the result set.
回答3:
As per Doug's answer, not loading a .doc() allowed me to get all the records. I had tried this earlier but the console.log was quite difficult to read. Adding a forEach from this StackOverflow answer
helped out.
router.get('/firebase', function (req, res) {
var admin = require('firebase-admin');
const firebaseConfig = require('../firebaseConfig.json');
admin.initializeApp({
credential: admin.credential.cert(firebaseConfig),
databaseURL: 'https://***.firebaseio.com'
});
let db = admin.firestore();
db.collection('marketing').get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting document', err);
});
});
来源:https://stackoverflow.com/questions/59121500/trying-to-load-all-firestore-documents-in-node-js