I'm using the Firebase Admin SDK with Node.js. My Firebase app has some Firestore databases. For example:
But every time I save data, it always goes to the (default)
database and I need to change it to the other database. I searched the Firebase documentation, but couldn't find anything.
What I tried:
databaseURL
:admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com',
})
initializeApp
function with the name of the DB:admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<APP_ID>.firebaseio.com',
}, '<DATABASE_NAME>') // this change the app, no the database 🤦♂️
I found the solution after inspecting firebase-admin's TypeScript types. I don't know if the Firebase documentation mentions this, but I didn't find it there. The solution is simple:
Change the Firestore database by setting the databaseId in the object passed to firestore().settings()
.
Here's an example to help you understand:
const admin = require('firebase-admin')
const serviceAccount = require('./serviceAccountKey.json')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<YOUR_APP_ID>.firebaseio.com',
})
admin.firestore().settings({
ignoreUndefinedProperties: true,
databaseId: 'system', // Here you change your DB
})
const db = admin.firestore()