How to CRUD with Node.js and MongoDB

MongoDB was one of the first NoSQL facts shops, and it is the most common NoSQL facts retailer these days. The Node.js JavaScript runtime continues to keep a dominate spot in back-finish improvement. With each other they make a highly versatile and dynamic technology stack.

As you will see, Node.js and MongoDB enable you to speedily employ critical application functionality like CRUD (build, study, update, and delete) functions. In this write-up, we’ll get a search at the CRUD essentials, applying the newest Node.js MongoDB driver (model three.six+).

Node.js and MongoDB set up

You are going to want Node.js and MongoDB mounted on your technique, and a command line with the curl command readily available. (If you are applying a Linux, MacOS, or Home windows ten model due to the fact 2018, you most likely have curl.)

You can down load MongoDB for your OS here. The moment downloaded, you can install it as a services or run it as an executable. Both way, be certain that MongoDB is jogging by opening a command line and jogging the mongo command. (You may well want to add the command to your route if you didn’t install as a services.) This provides you accessibility to the MongoDB instance jogging on your technique.

Following, be certain that you have Node.js and npm mounted. At the command line, kind node -v. If Node.js is mounted, you will get the model quantity. If not, go to the Node.js down load page and install Node on your machine.

Curl will allow you to accomplish very simple HTTP requests from the command line. For instance, if you run curl www.google.com you will get the markup from the Google principal page.

Develop a Node.js task

Now go to a practical folder wherever you will build a new task. Form npm init. For the task title, use node-mongo-intro. You can acknowledge the other defaults.

Now add the dependencies you want. In the task listing you just designed, kind npm install mongodb polka --conserve. This will install each the Node.js driver for MongoDB (permitting your task to accessibility MongoDB) and the Polka HTTP server, which you will use for managing HTTP requests.

Edit the offer.json file to include things like a commence script, as in Listing 1.

Listing 1. A commence script

"scripts": 
    "check": "echo "Mistake: no check specified" && exit 1",
    "commence": "node src/index" // <-- add this line
  ,

Now build a /node-mongo-intro/src/index.js file, and put the contents of Listing two in it.

Listing two. HTTP check in index.js

const polka = demand('polka')

polka()
  .get('/create', (req, res) =>
    res.finish(`works`)
  )
  .hear(3000, err =>
    if (err) throw err
    console.log(`> Jogging on localhost:3000`)
  )

Now commence the server with npm run commence. The server will hear on port 3000. You can check it with curl http://localhost:3000/build. If you do, you ought to see the response (alongside with some curl ask for details) of “works.”

Insert a report in MongoDB

Now we’re heading to accomplish a very simple insert. This is the C in CRUD. Update the index.js file to search like Listing three.

Listing three. A very simple insert

const polka = demand('polka')
const MongoClient = demand("mongodb")

polka()
  .get('/create', (req, res) => {
    const shopper = new MongoClient("mongodb://localhost:27017")
    async perform run()
      try
        await shopper.hook up()
        const databases = shopper.db("intro")
        const collection = databases.collection("quotations")

        const outcome = await collection.insertOne("estimate":"Existence is what takes place to you even though you're hectic building other options.")
        res.finish(JSON.stringify(outcome))
      catch (e)
        console.log("Mistake: " + e)
      lastly
        await shopper.near()
     
   
    run().catch(console.dir)
  })
  .hear(3000, err =>
    if (err) throw err
    console.log(`> Jogging on localhost:3000`)
  )

The code in Listing three opens a relationship to the MongoDB instance on your community technique, then specifies a databases ("intro") and collection ("quotations"). A collection is analogous to a table in a relational databases.

Following, the code inserts a document (analogous to a SQL report) and sends the results back in an HTTP response.

Run the insert

1st, end and restart the node server by hitting Ctrl-C. Then run this command at the command line: 

npm run startcurl http://localhost:3000/build

Validate the insert

One particular matter you will notice if you appear from a SQL history is that we didn’t build a table and schema before we did this get the job done. We didn’t even build the databases we utilised. MongoDB does all of this for us, and it can acknowledge any variety of structured crucial-benefit document into the collection.

Open the mongo shell with mongo, and enter the command use intro. This switches to the intro databases that was automatically designed. Now enter the db.quotations.locate() command, and you will see that the report was inserted. Discover that MongoDB automatically generated a exclusive ID on the "_id" industry. You can override this by specifying one you on the document.

Retrieve a document in MongoDB

Now let’s get the document back out. Include the .get() mapping observed in Listing 4. This is the R in CRUD.

Listing 4. Retrieve a document

.get('/retrieve', (req, res) => {
    const shopper = new MongoClient("mongodb://localhost:27017")
    async perform run()

      try
        await shopper.hook up()
        const databases = shopper.db("intro")
        const collection = databases.collection("quotations")

        const cursor = collection.locate(, )

        let goods = []
        await cursor.forEach(perform(doc)
          goods.thrust(doc)
        )
        res.finish(JSON.stringify(goods))
      catch (error)
        console.alert("Mistake: " + error)
        if (errCallback) errCallback(error)
      lastly
        await shopper.near()
     
   
    run().catch(console.dir)
  })

Listing 4 connects in the identical vogue as in Listing three, then troubles a locate command, with an empty question. This signifies it matches all files. Following it takes the response and marshals it into an array to be despatched back to the shopper.

Discover that the cursor functions are asynchronous, as is the collection.insertOne operation from Listing three. We use the await key word to handle these with out nested callbacks.

Examination the new endpoint (right after halting and beginning the server once more) with curl http://localhost:3000/retrieve and you will see the collection is returned.

Update a document in MongoDB

Now for the U in CRUD. This is managed in Listing five.

Listing five. Updating a document

.get('/update', (req, res) => {
    const shopper = new MongoClient("mongodb://localhost:27017")
    async perform run() {
      try
        await shopper.hook up()
        const databases = shopper.db("intro")
        const collection = databases.collection("quotations")

        const updateDoc =
          $established:
            author:
              "John Lennon",
          ,
       

        const outcome = await collection.updateOne(, updateDoc, ) // <-- empty filter matches all docs
        res.finish("Current: " + outcome.modifiedCount)
      catch (e)
        errCallback(e)
      lastly
        await shopper.near()
     
    }
    run().catch(console.dir)
  })

Listing five once more connects to the databases, then results in an update document. This document tells MongoDB what to change, by specifying a $established industry made up of an item with the fields and values to change. In our circumstance, we established the author industry to "John Lennon", the quoter of the estimate in concern.

Following, Listing five utilizes the updateOne() perform to execute the update doc. That closing empty-item argument is the filter. In this circumstance, we want to match on all files, so we go away it blank.

At last, we send out back the quantity of files we updated (one).

Delete a document in MongoDB

The closing letter in the CRUD acronym is D for delete.

The mapping for the delete operation is demonstrated in Listing six.

Listing six. Deleting a document

.get('/delete', (req, res) => {
    const shopper = new MongoClient("mongodb://localhost:27017")
    async perform run()
      try
        await shopper.hook up()
        const databases = shopper.db("intro")
        const collection = databases.collection("quotations")
        const question =
        const outcome = await collection.deleteOne(question)
        if (outcome.deletedCount === 1)
          res.finish("Effectively deleted one document.")
        else
          res.finish("Deleted files.")
       
      lastly
        await shopper.near()
     
   

Below once more we use an empty question to match all of the files in the "quotations" collection. The async collection.deleteOne() perform returns a outcome telling us how many files have been impacted.

Restart the server (Ctrl-C) and concern a new curl command:

curl http://localhost:3000/delete

You can validate the doucument has been deleted with curl http://localhost:3000/retrieve.

Dynamic CRUD duo

And there you have it, the comprehensive lifecycle for a document in the MongoDB facts retailer: build, study, update, and delete.

The Node.js and MongoDB combo (with some enable from Polka) makes for a extremely speedy and versatile improvement expertise. Master extra about Node.js here and extra about MongoDB and other NoSQL facts shops here.

Copyright © 2021 IDG Communications, Inc.