Home > Mobile >  Typescript MongoDB Prisma: List all databases programmatically
Typescript MongoDB Prisma: List all databases programmatically

Time:08-12

Is there any way to list all databases on a MongoDB server via Prisma programmatically with typescript?

CodePudding user response:

You can use the $runCommandRaw prisma function to list all the databases.

main.ts

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: ['query'],
});

async function main() {
  const output = await prisma.$runCommandRaw({ listDatabases: 1 });

  console.log(output);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Here's the output:

> ts-node index.ts

{
  databases: [
    { name: 'prisma', sizeOnDisk: 57344, empty: false },
    { name: 'sample_airbnb', sizeOnDisk: 55226368, empty: false },
    { name: 'sample_analytics', sizeOnDisk: 9609216, empty: false },
    { name: 'sample_geospatial', sizeOnDisk: 1437696, empty: false },
    { name: 'sample_mflix', sizeOnDisk: 56508416, empty: false },
    { name: 'sample_restaurants', sizeOnDisk: 8863744, empty: false },
    { name: 'sample_supplies', sizeOnDisk: 1191936, empty: false },
    { name: 'sample_training', sizeOnDisk: 62578688, empty: false },
    { name: 'sample_weatherdata', sizeOnDisk: 3694592, empty: false },
    { name: 'admin', sizeOnDisk: 339968, empty: false },
    { name: 'local', sizeOnDisk: 4137603072, empty: false }
  ],
  totalSize: 4337111040,
  totalSizeMb: 4136,
  ok: 1
}

Please make sure that to run listDatabases command you need to be on the admin database, so your connection string should point to admin database

Example:

DATABASE_URL="mongodb srv://username:[email protected]/admin"
  • Related