skip to Main Content

So basically I’m trying to get all the documents (as it’s called in Mongodb) in a collection. I’ve watched some Youtube videos and they use the db.collection.find() method to do this.

In my case however this doesn’t work for some reason. I’m using node js take a look at my code below.

import { MongoClient } from 'mongodb';

const client = new MongoClient(uri);
const database = client.db(dbase);
const collection = database.collection(collec);

const getAll = async () => {
    const res = await collection.find({});
    await client.close();
    return res;

console.log(getAll);

I was expecting some sort of an object or maybe an array of objects but unfortunatly I get this:

<ref *1> FindCursor {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  [Symbol(kCapture)]: false,
  [Symbol(client)]: MongoClient {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,

I’m not going to show the full error message since it contains sesetive information but this is the first few lines which I think should be save to share.

Thanks in advance…

2

Answers


  1. Chosen as BEST ANSWER

    Found the answer

    const getAll = async () => {
      const cursor = COL.find({});
      await cursor.forEach((doc) => console.log(doc));
    };
    

    or

    const getAll = async () => {
        const res = await collection.find({}).toArray();
        await client.close();
        return res;
    }
    
    console.log(getAll())
    

    credit to Sou for the second answer!


  2. You need to call the toArray() function to get the array of results.

    const getAll = async () => {
        const res = await collection.find({}).toArray();
        await client.close();
        return res;
    }
    
    console.log(getAll())
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search