How to CRUD with Node.js and MongoDB

MongoDB was one of the first NoSQL data stores and Most Popular NoSQL Data Store today is Node.js The JavaScript runtime continues to dominate backend development. The combination of these creates a highly flexible and dynamic technology stack.

As you can see, Node.js and MongoDB allow you to quickly implement important application features like CRUD (Create, Read, Update, Delete) operations. In this article, we’ll use the latest Node.js MongoDB driver (version 3.6 and above) to explore the basics of CRUD.

Configuring Node.js and MongoDB

Node.js and MongoDB must be installed on your system and on the command line curl The order is available. (If you are using Linux, MacOS, or Windows 10 versions after 2018, you loop..)

You can download MongoDB for your operating system. HereOnce downloaded, you can install it as a service or run it as an executable file. Either way, make sure MongoDB is running by opening the command line and running: mongo order. (If you haven’t installed it as a service, you might need to add the command to your path.) This will give you access to the MongoDB instance running on your system.

Then make sure Node.js and npm are installed. On the command line, type: node -vIf you have installed .Node.js, get the version number. Otherwise, go to Node.js download page Install Node on your machine.

Curl allows you to make simple HTTP requests from the command line. For example, if you want to run curl www.google.com You will receive the markup for the main page from Google.

Create a Node.js project

Navigate to a handy folder where you can create a new project type npm initUse node-mongo-intro for the project name. Other default values ​​may be accepted.

Then add the required dependencies. In the directory of the project you just created, type: npm install mongodb polka --saveThis will allow the Node.js driver for MongoDB (which will allow your project to access MongoDB) and Polka HTTP Server, Used to handle HTTP requests.

Edit the package.json file to include the startup script as shown in List 1.

List 1. Run the script

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node src/index" // <-- add this line
  },

Then create the file /node-mongo-intro/src/index.js and place the content of Listing 2 in it.

Listing 2. HTTP test with index.js

const polka = require('polka');

polka()
  .get('/create', (req, res) => {
    res.end(`works`);
  })
  .listen(3000, err => {
    if (err) throw err;
    console.log(`> Running on localhost:3000`);
  });

Start the server with npm run startThe server listens on port 3000. You can test it with the following command: curl http://localhost:3000/createWhen you run it, you should see a “working” response (with information about the curl request).

Insert a record in MongoDB

Then perform a simple insertion. It’s C in CRUD.Update index.js Edit the file as shown in Listing 3.

List 3. Simple insertion

const polka = require('polka');
const { MongoClient } = require("mongodb");

polka()
  .get('/create', (req, res) => {
    const client = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await client.connect();
        const database = client.db("intro");
        const collection = database.collection("quotes");

        const result = await collection.insertOne({"quote":"Life is what happens to you while you're busy making other plans."});
        res.end(JSON.stringify(result));
      } catch (e) {
        console.log("Error: " + e);
      } finally {
        await client.close();
      }
    }
    run().catch(console.dir);
  })
  .listen(3000, err => {
    if (err) throw err;
    console.log(`> Running on localhost:3000`);
  });

The code in Listing 3 opens a connection to a MongoDB instance on your local system and specifies the database ("intro") And the collection ("quotes"). A collection is similar to a table in a relational database.

The code then inserts a document (similar to an SQL record) and returns the result in an HTTP response.

Perform the insertion

First, press Ctrl-C to stop and restart the node server. Then run the following command on the command line:

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

Confirm insertion

One thing anyone with SQL training knows is that they hadn’t created the tables and schemas before they did. I did not create the database I used. MongoDB can do all of this and accept any kind of structured key and value document in the collection.

Open the mongo shell with mongo, Enter the command use introThis will switch to the automatically created intro database. following, db.quotes.find() When you run the command, you can see that the record has been inserted. Note that MongoDB automatically generated a unique identifier. "_id" field. You can override this by specifying it yourself in the documentation.

Get documentation with MongoDB

Now let’s get the documentation. .get() The mapping shown in Listing 4. This is R for CRUD.

List 4. Get the document

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

      try {
        await client.connect();
        const database = client.db("intro");
        const collection = database.collection("quotes");

        const cursor = collection.find({}, {});

        let items = [];
        await cursor.forEach(function(doc){
          items.push(doc);
        });
        res.end(JSON.stringify(items));
      } catch (error){
        console.warn("ERROR: " + error);
        if (errCallback) errCallback(error);
      } finally {
        await client.close();
      }
    }
    run().catch(console.dir);
  })

Listing 4 connects in the same way as Listing 3, then find Command, empty request. This means that it matches all documents. It then receives the response, groups it in a table, and sends it back to the customer.

Note that cursor operations are asynchronous. collection.insertOne List operation 3. await Keywords that handle them without nested callbacks.

Test the new endpoint (after stopping and restarting the server) curl http://localhost:3000/retrieve You can see that the collection is returned.

Update documentation in MongoDB

Now let’s talk about U in CRUD. This is covered in Listing 5.

List 5. Document updates

.get('/update', (req, res) => {
    const client = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await client.connect();
        const database = client.db("intro");
        const collection = database.collection("quotes");

        const updateDoc = {
          $set: {
            author:
              "John Lennon",
          },
        };

        const result = await collection.updateOne({}, updateDoc, {}); // <-- empty filter matches all docs
        res.end("Updated: " + result.modifiedCount);
      } catch (e) {
        errCallback(e);
      } finally {
        await client.close();
      }
    }
    run().catch(console.dir);
  })

Listing 5 reconnects to the database and creates an update document. This document tells MongoDB what to change. $set A field that contains an object with a field and a value to modify. In our case author To the field "John Lennon", The citation of the citation of the problem.

Then in list 5 updateOne() A function that executes an update document. The last empty object argument is a filter. In this case, leave it blank because it must match in all documents.

Finally, we will return the number of updated documents (1).

Delete documents in MongoDB

The last letter of the acronym CRUD is D, which stands for delete.

Listing 6 shows the mapping of delete operations.

List 6. Delete document

.get('/delete', (req, res) => {
    const client = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await client.connect();
        const database = client.db("intro");
        const collection = database.collection("quotes");
        const query = { };
        const result = await collection.deleteOne(query);
        if (result.deletedCount === 1) {
          res.end("Successfully deleted one document.");
        } else {
          res.end("Deleted 0 documents.");
        }
      } finally {
        await client.close();
      }
    }

Again, using an empty query, "quotes" collection.asynchronous collection.deleteOne() The function returns a result indicating the number of documents affected.

Restart the server (Ctrl-C) and issue a new curl command.

curl http://localhost:3000/delete

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

Dynamic CRUD duo

You now have a full lifecycle (create, read, update, delete) of documents in your MongoDB datastore.

The combination of Node.js and MongoDB (with help from Polka) provides a very fast and flexible development experience. Node.js details Here About MongoDB and other NoSQL datastores Here..

Copyright © 2021 IDG Communications Co., Ltd.


Source link

About Jon Moses

Check Also

The new candidate version of X.Org Server appears after a long delay • The registry

More than three years after X.Org Server 1.20, released in May 2018, a release candidate …

Leave a Reply

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