Luis Michael Luethi
Luis Michael Luethi

Reputation: 69

MongoDb: Accessing Collection and console log Object

I am trying to access a MongoDB Collection and I want to console.log a Object from this Collection.

I connect to my MongoDB as follows:

async function main(){
  /**
   * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
   * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
   */
  const uri = process.env.DB_Port;
  const client = new MongoClient(uri,{ useNewUrlParser: true, useUnifiedTopology: true});

  try {
      // Connect to the MongoDB cluster
      await client.connect();

      // Make the appropriate DB calls
      await  listDatabases(client);

  } catch (e) {
      console.error(e);
  } finally {
      await client.close();
  }
  
}

main().catch(console.error);

async function listDatabases(client){
  databasesList = await client.db().admin().listDatabases();

  console.log("Databases:");
  databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

This console logs:

Databases:
 - radiototem
 - test
 - admin
 - local

Now I want to access the collection test and console log everything that is inside it. How can I achieve this?

Best regards

Upvotes: 0

Views: 1131

Answers (1)

LukeZz
LukeZz

Reputation: 301

In order to get items from MongoDB, you first need to access the collection in which they are stored. Collections in MongoDB are basically the same as tables in SQL.

To get a collection, call the .collection() function on your DB object you get from client.db() with the name of your collection like this:

client.db().collection('test');    // This gives you the collection "test"

If you want to get items from a collection, you can use the .find() method. You can pass it a query parameter which is an object where you define, which items should be selected based on their properties.

Example, get all users named peter from the users collection:

const db = client.db();
const users = db.collection('users');
const usersNamedPeterCursor = users.find({ name: 'Peter' });

Now if you want to get all items from a collection, you can simply use the find method without the query parameter. This will return all items from the collection.

The find method returns a Cursor object which lets you interact with the returned data. You can call methods on the Cursor object like max(), min(), toArray(), each() and many more.

So, if you want to console.log every item in your collection you can do it like this:

client.db().collection('test').find().each(function(error, item) {
 // console .log your item or do something else with it
});

Upvotes: 1

Related Questions