Next.js Discord

Discord Forum

can't list a mongodb collections

Unanswered
Cape horse mackerel posted this in #help-forum
Open in Discord
Cape horse mackerelOP
import { db } from '@/lib/db';
export default async function handler(req, res) {
  try {
    const collections =  await db.listCollections().toArray();

    return res.status(200).json({ message: 'Collections retrieved successfully', collections });
  } catch (error) {
    console.error('Error listing collections:', error);

    return res.status(500).json({ error: 'Failed to list collections', details: error.message });
  }
}


I am getting

Error listing collections: TypeError: _lib_dbWEBPACK_IMPORTED_MODULE_0.db.listCollections is not a function

9 Replies

Cape horse mackerelOP
Is this specific to using /lib/db?
Pacific sand lance
can u show how tu create db instance
@Pacific sand lance can u show how tu create `db` instance
Cape horse mackerelOP
means?
This is a working api

import { db } from '@/lib/db';
import serverAuth from '@/lib/serverAuth';

const layoutName = 'Premium';

export default async function handler(req, res) {
  const { currentUser } = await serverAuth(req, res);
  if (req.method === 'GET') {
    console.log('custom theme color palette API GET request');
    try {
      const userId = currentUser.id;

      if (!userId) {
        return res.status(400).json({ error: 'userId is required' });
      }

      const dbUser = await db.user.findFirst({
        where: { id: userId },
      });

      if (!dbUser) {
        return res.status(400).json({ error: 'User is not identified' });
      }

      const themeType = await db.themeType.findFirst({
        where: { userId },
      });
import { PrismaClient } from '@prisma/client';

let prisma;
if (typeof window === 'undefined') {
  if (process.env.NODE_ENV === 'production') {
    prisma = new PrismaClient();
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient();
    }
    prisma = global.prisma;
  }
}

export const db = prisma;
Yacare Caiman
why you are checkin window undefiend? just add "use server" and remove the unessarcy conditions
@Yacare Caiman why you are checkin window undefiend? just add "use server" and remove the unessarcy conditions
Pacific sand lance
rather server-only in this case.
I just used the dB instance everywhere