Introduction to Node.js with MongoDB — Part 1
In our previous blog, we explored the basic CRUD actions with MongoDB from the Mongo Shell, the list of commands is available at my Github page. This week we will continue our journey and look at how Node.js can work hand-in-hand with MongoDB.
Before we get started, please make sure you have MongoDB installed in your machine. You can refer to my previous blog on installing MongoDB. I will be running it locally, if you prefer to run MongoDB Atlas on the cloud, that’s totally fine.
The second requirement is you should be familiar with JavaScript concepts such as variables, classes, and functions. If Node.js is not already installed, you can download and install either the current or the long term support version from the official website. After installation, when you run node -v and npm -v on your Terminal, you should see the version numbers similar to the below image:
And if you remember from last week’s blog, we can start MongoDB locally as a service by running this command: brew services start mongodb-community@4.4 then run mongo, if connected successfully, this is what you should see:
Notice after MongoDB shell version, the line where it says connecting to: mongodb://127.0.0.1:27017. This is the hostname and port number (27017 is the default port number used by MongoDB) where we will connect to in our Node.js script. The part after the port number are connection options.
Let’s create a folder named node-mongo-project and navigate to that folder at Terminal. First we will run npm init, you can press enter to skip over the prompts, everything can be left as is for now. This command will create a package.json file where you can see a list of your dependencies as well as other information. Next run npm install mongodb. Afterward the installation, your package.json file should look like this:
We will create our index.js file now and load in our mongodb module as well as create a MongoClient object like so:
Line one is the same as these 2 lines: var mongo = require(‘mongodb’); var MongoClient = mongo.MongoClient; The one-liner just loads in the module and creates the MongoClient at the same time.
Next we will have our client connect to a database, if that said database does not exist, MongoDB will first create it then connect to it.
On line 3, we create a url variable and point it to our hostname and port from when we connected to MongoDB using the Mongo Shell earlier. mydb is the name of our new database, MongoDB will go ahead and create this database since it does not exist at this point and time. If however it did exist, MongoDB will connect to it.
You can run the file with the command node index.js or just node index, from the terminal, you should get an output stating “Database created…”. The codes so far are same as running use mydb at the Mongo Shell, you will still need to have a collection within the database before it shows up with the command show dbs. Let’s create a collection next.
From line 7, calling the Mongodb.db() method with the name of the database as argument will return a database object that allows us to access collections in that database. On the next line, we create a collection named pets. This is the same as calling the db.createCollection(‘pets’) on Mongo Shell. After running the file, when we return Mongo Shell, we should see the database and pets collection already create:
Next we will look at how to insert document (or multiple documents) into a collection. If you recall, the Mongo shell commands we used were db.pets.insert() and db.pets.insertMany(). And in Node.js, they are insertOne() and insertMany().
We can also create an object containing key value pairs of what to insert, then pass in that object as an argument to the insertOne() method like so:
Same with inserting in the Mongo Shell, if the collection does not exist, it will be created automatically.
To insert more than one document, we can create an array of those objects and use the insertMany() method like so:
Here’s the result after running our insert_multiple_docs.js file:
To search for documents in a collection, we use the find() and findOne() methods, which return all matched results and first matched result respectively.
For instance, let’s say we want to find a cat by its name, we can use findOne() and pass in a query object as the first argument, we can see the search in the terminal on the bottom of the screen. The document with the name amber is returned:
If we were to find all wild cats, we can use the find() method pass in wild: true query object:
Notice if you don’t pass in any query object arguments, those methods will just return the first (findOne) and all (find) documents.
Next week we will continue to explore the other CRUD functionalities with Node.js and MongoDB. You can download the code for today’s blog at my Github page. Have fun learning and coding!