MongoDB query returns topology instead of documents

Viewed 35

I am using MonogDB and NextJS. I am trying to build an endpoint to return all the users. Instead, I get a response of

{
"_events": {},
"_eventsCount": 0
}

I am using this code to query the database:

import { connectToDatabase } from "../../src/util/mongodb";

export default async function buildUser(req, res){
  const { db } = await connectToDatabase();


  const users = await db.collection("users").find();
  res.status(200).json(users)
}

And here is the connectToDatabase function:


import { MongoClient } from 'mongodb'

let uri = process.env.MONGODB_URI
let dbName = process.env.MONGODB_DB

let cachedClient = null
let cachedDb = null

if (!uri) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}

if (!dbName) {
  throw new Error(
    'Please define the MONGODB_DB environment variable inside .env.local'
  )
}

export async function connectToDatabase() {
  if (cachedClient && cachedDb) {
    return { client: cachedClient, db: cachedDb }
  }

  const client = await MongoClient.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })

  const db = await client.db(dbName)

  cachedClient = client
  cachedDb = db

  return { client, db }
}

I am able to get all the users using the mongosh shell and am unsure why I get _events and _eventsCount here.

1 Answers

find returns a Cursor, these are just some of it's properties. all you need to do is add the toArray() function:

const users = await db.collection("users").find({}).toArray();

Now this will return the array of documents as expected.

Related