Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Cursor

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Event API

We can get query results from our collection with Node.js’s Event API.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    cursor.on("data", data => console.log(data));
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to watch for the 'data' event so that we can get the data from the result.

Fetch Results as an Array

We can ferch results as an array.

For instane, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const allValues = await cursor.toArray();
    console.log(allValues);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call the toArray method on the cursor which returns a promise that resolves to the result from test collection.

Cursor Utility Methods

The cursor object has a few utility methods.

The count method returns the number of results retrieved from a collection.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const count = await cursor.count();
    console.log(count);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to get the items returned from the query.

The rewind method lets us reset the cursor to its initial position in the set of returned documents.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany([
      {
        name: "Popeye",
        rating: 5,
        qty: 100
      },
      {
        name: "KFC",
        rating: 4,
        qty: 121
      },
    ]);
    console.log(result)
    const query = {
      name: "Popeye",
    };
    const cursor = testCollection.find(query);
    const firstResult = await cursor.toArray();
    console.log("First count: ", firstResult.length);
    await cursor.rewind();
    const secondResult = await cursor.toArray();
    console.log("Second count: ", secondResult.length);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We called rewind and get the result from the cursor before and after calling rewind .

We get the same result in each console log because we called rewind to reset the cursor.

Conclusion

We can listen to the data event and get the data from there.

Also, we can use the cursor to do various retrieval operations.

Leave a Reply

Your email address will not be published. Required fields are marked *