Node.js - MongoDB Database Connection

Exercise 1 Establishing connection with the database and fetching all the databases

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
    const client = new MongoClient(uri);
 
    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}`));
};
    
Output
    PS F:\Winter Semester 2022-23\codedemo> node first.js
      Databases:
       - admin
       - config
       - local
       - satishdb
       - vitdb
    PS F:\Winter Semester 2022-23\codedemo>

Insert a record in the collection by named vscode in database vitdb

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
         // Create a single new listing
         await insertDocument(client,
            {
                name: "Satish",
                summary: "Satish is teaching MongoDB"
            }
        );      
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);


async function insertDocument(client, newListing){
    const result = await client.db("vitdb").collection("vscode").insertOne(newListing);
    console.log(`New listing created with the following id: ${result.insertedId}`);
}
    
Output
    PS F:\Winter Semester 2022-23\codedemo> node first.js
    New listing created with the following id: 6432ba80e40381b7aa9547c9
    PS F:\Winter Semester 2022-23\codedemo> 

Record inserted on mongo database

 
      > db.vscode.find();
{ "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew", "course" : "testing db connection" }
{ "_id" : ObjectId("6432b9c59061f67fa5c2d6f5"), "name" : "Ram", "summary" : "Testing Inserting a Record" }
{ "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish", "summary" : "Satish is teaching MongoDB" }
    

search for a document (search for document with the name attribute as Satish)

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        //search for one record 
        await findUser(client, "Satish");
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);


async function findUser(client, username) {
    const result = await client.db("vitdb").collection("vscode").findOne({ name: username });

    if (result) {
        console.log(`Found a listing in the collection with the name '${username}':`);
        console.log(result);
    } else {
        console.log(`No listings found with the name '${nameOfListing}'`);
    }
}
    
output from terminal
    PS F:\Winter Semester 2022-23\codedemo> node first.js
    Found a listing in the collection with the name 'Satish':
    {
      _id: new ObjectId("6432ba80e40381b7aa9547c9"),
      name: 'Satish',
      summary: 'Satish is teaching MongoDB'
    }

Reading Multiple Documents from Mongodb

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        await findUsers(client, {
            name: 'Satish'
        });
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);


async function findUsers(client, {username = 'Satish'} = {}) {

    const cursor = client.db("vitdb").collection("vscode")
        .find({name: 'Satish'})

    // Store the results in an array
    const results = await cursor.toArray();

    // Print the results
    if (results.length > 0) {
        results.forEach((result, i) => {
            console.log();
            console.log(`name: ${result.name}`);
            console.log(`   summary: ${result.summary}`);
        });
    } else {
        console.log(`No listings found`);
    }
}
    
output from terminal
    PS F:\Winter Semester 2022-23\codedemo> node first.js

    name: Satish
       summary: Satish is teaching MongoDB
    
    name: Satish
       summary: another record

Reading all Records from a collection in Mongodb

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        await findUsers(client, {});
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);


async function findUsers(client, {} = {}) {

    const cursor = client.db("vitdb").collection("vscode")
        .find({})

    // Store the results in an array
    const results = await cursor.toArray();

    // Print the results
    if (results.length > 0) {
        results.forEach((result, i) => {
            console.log();
            console.log(`name: ${result.name}`);
            console.log(`   summary: ${result.summary}`);
        });
    } else {
        console.log(`No listings found`);
    }
}
    
output from Terminal
    PS F:\Winter Semester 2022-23\codedemo> node first.js

    name: Mathew
       summary: undefined
    
    name: Ram
       summary: Testing Inserting a Record
    
    name: Satish
       summary: Satish is teaching MongoDB
    
    name: Satish
       summary: another record

Updating a record using the username

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        await updateUserSummary(client, "Mathew", { summary:"Updated summary"});
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);


async function updateUserSummary(client, username, updatedSummary) {
    const result = await client.db("vitdb").collection("vscode").updateOne({ name: username }, { $set: updatedSummary });

    console.log(`${result.matchedCount} document(s) matched the query criteria.`);
    console.log(`${result.modifiedCount} document(s) was/were updated.`);
}
    
output from Terminal
    PS F:\Winter Semester 2022-23\codedemo> node first.js
    1 document(s) matched the query criteria.
    1 document(s) was/were updated.
Output in Database
    > db.vscode.find();
    { "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew", "course" : "testing db connection", "summary" : "Updated summary" }
    { "_id" : ObjectId("6432b9c59061f67fa5c2d6f5"), "name" : "Ram", "summary" : "Testing Inserting a Record" }
    { "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish", "summary" : "Satish is teaching MongoDB" }
    { "_id" : ObjectId("6432bf0a86b0db063f0ec8b3"), "name" : "Satish", "summary" : "another record" }

Deleting a document from the Collection

 
      const {MongoClient} = require('mongodb');
async function main(){
    
    const uri = "mongodb://127.0.0.1:27017/";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        await deleteByName(client, "Ram");
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);

async function deleteByName(client, nameOfUser) {
    const result = await client.db("vitdb").collection("vscode").deleteOne({ name: nameOfUser });
    console.log(`${result.deletedCount} document(s) was/were deleted.`);
}
    
output from Terminal
    PS F:\Winter Semester 2022-23\codedemo> node first.js
    1 document(s) was/were deleted.
Database Output
    > db.vscode.find();
    { "_id" : ObjectId("64327ce9bb103b2a3a353b7e"), "name" : "Mathew", "course" : "testing db connection", "summary" : "Updated summary" }
    { "_id" : ObjectId("6432ba80e40381b7aa9547c9"), "name" : "Satish", "summary" : "Satish is teaching MongoDB" }
    { "_id" : ObjectId("6432bf0a86b0db063f0ec8b3"), "name" : "Satish", "summary" : "another record" }
    >