Search code examples
javascriptnode.jsfirebasegoogle-cloud-firestorefirebase-admin

How can I connect to a non-default firestore database using Node (using multiple firestore databases)?


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!


Solution

  • 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.

    npm install firebase-admin@latest --save