Using firebase-admin To Connect to a Firestore Database other than (default)
Use a firebase-admin Package with multi-db Support
Before reading on, make sure you have a recent enough version of firebase-admin
installed (from what I read, 11+ has multi-db support). Otherwise install it with npm install firebase-admin@lates
:
$ npm list firebase-admin
firebase-admin@1.0.0 ~/projects/firebase-setup/firebase-admin
└── firebase-admin@13.2.0
Use settings() to set the DB
This is what you came here for, the settings()
call.
Set the databaseId
with the settings()
call
const admin = require('firebase-admin');
admin.initializeApp({ /* ... */ });
const db = admin.firestore();
db.settings({ databaseId: 'my-other-db' }); // THIS WORKS
AI suggested variations of the following
const db = admin.firestore({ databaseId: 'my-other-db' }); // won't work
const db = admin.firestore().database('my-other-db'); // won't work
const db = admin.firestore().databaseId('my-other-db'); // won't work
All of those result in errors similar to these:
~/projects/firebase-setup/firebase-admin/node_modules/firebase-admin/lib/app/firebase-namespace.js:136
return this.ensureApp(app).firestore();
^
TypeError: this.ensureApp(...).firestore is not a function
at FirebaseNamespace.fn (~/projects/firebase-setup/firebase-admin/node_modules/firebase-admin/lib/app/firebase-namespace.js:136:40)
at Object.<anonymous> (~/projects/firebase-setup/firebase-admin/backup-db.js:12:18)
at Module._compile (node:internal/modules/cjs/loader:1554:14)
at Object..js (node:internal/modules/cjs/loader:1706:10)
at Module.load (node:internal/modules/cjs/loader:1289:32)
at Function._load (node:internal/modules/cjs/loader:1108:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
at node:internal/main/run_main_module:36:49
Node.js v22.14.0
const db = admin.firestore().database('my-other-db');
^
TypeError: admin.firestore(...).database is not a function
at Object.<anonymous> (~/projects/firebase-setup/firebase-admin/backup-db.js:12:30)
at Module._compile (node:internal/modules/cjs/loader:1554:14)
at Object..js (node:internal/modules/cjs/loader:1706:10)
at Module.load (node:internal/modules/cjs/loader:1289:32)
at Function._load (node:internal/modules/cjs/loader:1108:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
at node:internal/main/run_main_module:36:49
Node.js v22.14.0
Hope this helps someone.