NaveenSingh's Blog

NaveenSingh's Blog

CRUD Operation using Nodejs utterly for beginners level

In this Blog you can learn about CRUD operation using Nodejs, Which i was recently started learning about nodejs and thought of writing it as blog, If you are developer you might be familiar with the term CRUD operation, So don't want to go much deeper on that let's dive directly into the summary and concepts,

  1. How MongoDB stores the data.

  2. Create - Insertone

  3. Read - findOne

  4. Update - updateOne

  5. Delete - deleteOne

How MongoDB stores the data

First we have to understand how mongoDB stores the data, In MongoDB is all about the document, It's stores the data in BSON format, You might be familiar with JSON, But BSON sounds like weird right, Initially i too felt same, And It is not much complicated concepts,

BSON - Binary Represention of JSON document

Example

{
    _id: ObjectId("5009303df3f4548bd2f92391"),
    studentname: { first: "John", last: "David" },
    dob: new Date('Jun 23, 1912'),
    joiningdate: new Date('Jun 07, 1954'),
    talent: [ "Sports", "Drawing", "Poetry" ],
}

The exmaple describes about the BSON documents which includes the array,other document and array of other documents it stores data on the format of fields and values

  • _id : It is an objectid which unique key which is created automatically and it is an immutable.
  • studentname : holds an value and data type.
  • dob : It is an date data type.
  • talent : Array of strings.

In this blog series, We not gonna cover the how to connect the MongoDB atlas and cluster concepts, Only nodejs concepts, We'll use the student dataset an example. The student database contains one collection: listingsAndDetails. This collection contains documents about student listings and their details.

Create

Now let's create a new student listing from the dataset, By using the technique of InsertOne() from the name itself you can able to understand what does it mean, And it will be inserted one row from the dataset, Let's see how to implement the syntax and rule for insertOne() is

And it's only required new document (type of object) that will be inserted

async function createListing(client, newListing){
    const result = await client.db("sample_student").collection("listingsAndDetails").insertOne(newListing);
    console.log(`New listing id: ${result.insertedId}`);
}

MongoDB drivers automatically create an _id If document does not contain an _id

await createListing(client,
        {
            studentname: "John Dave",
            dob: 2018-01-23,
            class: 7,
            talent: [ "Sports", "Drawing", "Poetry" ]
        }
    );

// *Output*

// New listing id: 54933adee415264e135c5ec8

Read

Once the data is created now time to read the document, Let's see how to read the data, In the short to understand, Usually how we use to search the data in the database, Yes by using query with where condition, Same like that here also, But not using exact where condition, Here we use the technique like findOne() Same as like insertOne() from the name itself you can able to understand what it does actually mean, Right now we gonna search the student name we will include the name field in the query object

async function findOneListingStudentName(client, nameOfListing) {
    const result = await client.db("sample_student").collection("listingsAndDetails").findOne({ name: nameOfListing });

    if (result) {
        console.log(`Found a listing in the collection with the name '${nameOfListing}':`);
        console.log(result);
    } else {
        console.log(`No listings found with the name '${nameOfListing}'`);
    }
}

Now Calling the function by passing MongoClient

await findOneListingStudentName(client, "John Dave");


// Output 

Found a listing in the collection with the name 'John Dave':
{
    _id: 5da9b5983e104518671ae128,
    studentname: "John Dave",
    dob: 2018-01-23,
    class: 7,
    talent: [ "Sports", "Drawing", "Poetry" ]
}

Update

After creating and reading document, Now we needs to update the document which is created or exist document, By using updateOne() Let's update the student class to 8, In order to update we use $set , The Set operator to set new values or updating the existing document

async function updateListingByName(client, nameOfListing, updatedListing) {
  const result = await client.db("sample_student").collection("listingsAndDetails")
    .updateOne({
      name: nameOfListing
    }, {
      $set: updatedListing
    });

}

// Output 

{
    _id: 5da9b5983e104518671ae128,
    studentname: "John Dave",
    dob: 2018-01-23,
    class: 8,
    talent: [ "Sports", "Drawing", "Poetry" ]
}

Delete

Guess what after creating,reading and updating document, Yes now needs to see the delete data, In every crud operation personally i feel delete operation is much more easier to perform, we can delete the single document by using deleteOne() And it has option params, As i said like from the beginning from name itself you can easily understand, It will be deleted the one of document

async function deleteListingByStudentName(client, nameOfListing) {
  const result = await client.db("sample_student").collection("listingsAndDetails")
    .deleteOne({
      name: nameOfListing
    });
  console.log(`${result.deletedCount} document is deleted.`);
}
await deleteListingByStudentName(client, "John Dave");

// Output 
1 document is deleted.

And that's it.

The Concepts covered is completely basics there is lot more technique and methods are available, If you find anything wrong or any feedbacks, Please put on comments, So i can amend next time, And thanks for you time, For reading this blog. Stay happy and Stay cool!

 
Share this