I have multiple firestore databases in my project.
The databases were created using the command line and I can see it in the Firestore Databases preview following the instructions here: https://cloud.google.com/blog/products/databases/manage-multiple-firestore-databases-in-a-project
I am able to connect to the default database, but am having problems connecting to other named databases. I would like to be able to update/delete data in those other databases.
I am attempting to connect to the databases using the lastest firebase-admin sdk (11.10.1) which has support for multiple named databases (https://firebase.google.com/support/release-notes/admin/node)
I would like to use the functions getFirestore(databaseId)
or getFirestore(app, databaseId)
(https://firebase.google.com/docs/reference/admin/node/firebase-admin.firestore)
but am getting the following error when I try to save data:
Error: 3 INVALID_ARGUMENT: The request was for database ‘projects/testproject/databases/testdb’ but was attempting to access database ‘projects/testproject/databases/(default)’
My code looks like this:
const { getFirestore } = require('firebase-admin/firestore');
const {
initializeApp,
applicationDefault,
} = require('firebase-admin/app');
const app = initializeApp({
credential: applicationDefault(),
});
const db = getFirestore();
const otherFirestore = getFirestore('testdb');
const saveData = async (col, doc, data) => {
await otherFirestore
.collection(col)
.doc(doc)
.set(data, { merge: true });
};
If I use db instead of otherFirestore, the data is saved into my default database.
I have also tried doing a const otherFirestore = getFirestore(app, 'testdb');
but end up with the same error.
I am expecting the data to be saved to my testdb database.
Any help would be appreciated, thanks!
3
Answers
Thanks for all the help! Looks like it was my package was not being updated correctly despite having
"firebase-admin": "^11.10.1",
in my package.json. Had to run the following then trying it again seems to have fixed it.I just tried using multiple databases for the first time and it seems to be working with no errors. The only difference I see from your code is that I call initializeApp with no parameters. I’m also importing initializeApp and getFirestore differently (
import { getFirestore } from 'firebase-admin/firestore'
instead ofconst { getFirestore } = require('firebase-admin/firestore');
) – that shouldn’t make a difference, but maybe try that.After checking the comments and ideas at this post, here is my full solution:
To create a second, third firestore database, access Google Cloud, open Cloud Shell, select the project, running
“gcloud config set project [PROJECT_ID]”
and then run the command
"gcloud alpha firestore databases create –database=NAME – -location=LOCATION –type=firestore-native –delete-protection"
Then navigate to the firestore session as shown in the image below
I created the following code that is working for me to use more than one firestore database.