Member-only story

Node.js Basics — MongoDB Cursor and Sorting

John Au-Yeung
3 min readJan 20, 2021

--

Photo by Markus Spiske on Unsplash

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.

Closing the Cursor

To clean up any resources used after getting the results from a collection, we call the cursor.close method.

To do that, we 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 queryResult = await cursor.toArray();
console.log(queryResult);
await cursor.close();
} finally {
await client.close();
}
}
run().catch(console.dir);

--

--

No responses yet