Learning Node.js — Part 5

MongoDB

MongoDb is a document database², aka a NoSQL database. It’s not a relational database. There are no tables, schemas, views, records or columns¹ in a NoSQL db, instead the data is split up into collections, which are a lot like tables. These collections store documents, which resemble records (row in a table) in a SQL db. Documents, just like records, auto-generate a unique id (“_id”:). You store json objects in MongoDB and MongoDB gives us back json objects when we query our data.

Installing MongoDB — For Macs

Similar to npm, Homebrew is a package manager for MacOS. If you haven’t installed Homebrew previously, visit: https://brew.sh/ and install Homebrew. If you have Homebrew already installed, type in terminal command: brew update .

(This is different then Mosh’s example, bc mongodb has been removed from homebrew-core) After Homebrew is finished downloading, install MongoDB by typing the following terminal commands⁴:

  • xcode-select — install
  • brew tap mongodb/brew
  • brew install mongodb-community@4.4 ((please make sure to check docs to ensure you update the most up-to-date version))

Installing The MongoDB Community Locally⁵:

Install the download for ‘On-premises’ here. Open the zip file drag the file onto your desktop. To run MongoDB, we can always use this terminal command: ~/Desktop/mongodb-macos-x86_64–4.4.5/bin/mongo . But, we don’t want to have to type all of this each time we use MongoDB. In you user local bin, there are a number of different files that are one name executable in our terminal. To see the list, type in the following commands:

  • cd /usr/local/bin
  • ls

To include MongoDB as a one name executable file on our terminal command line: While inside that bin (for me the command line looks like this : /usr/local/bin ), copy whatever is in that downloaded files bin file into the user local bin ( example: sudo cp ~/Desktop/mongodb-macos-x86_64–4.4.5/bin/* /usr/local/bin ) ***Note***There is a space between the ‘*’’ and the ‘/’ in that command.

In order to set up the directory that MongoDB will store all of the data in, I had to do a little bit of sketchy SIP Disabling to continue, because with Mac’s Catalina update, they made the root folder readable only. Please see the instructions on how to do this disabling here.

While the root folder is writeable, In order to make the directory now in the root folder, run terminal command: sudo mkdir -p /data/db . To make sure that the folder exists, use terminal commands: cd /data , then ls . You should see ‘db’ listed. To give MongoDB permissions, type terminal commands:(1) sudo chmod 777 /data AND (2) sudo chmod 777 /data/db .

I did read that it the SIP is re-enabled as soon as you restart your computer, so do restart AFTER you have gone through their entire set of instructions, and then run the mkdir command above.

If in the terminal, you run command: mongod , you should see a line that looks something like “{“t”:{“$date”:”2021–04–22T11:55:32.665–06:00"},”s”:”I”, “c”:”NETWORK”, “id”:23016, “ctx”:”listener”,”msg”:”Waiting for connections”,”attr”:{“port”:27017,”ssl”:”off”}}”. We are looking for a message that shows ‘Waiting for connections’ along with a port number. SUCCESS! Mongod is the primary daemon process for the MongoDB system

Let’s check and make sure our DB is working. Start a new terminal window and type in command: mongo . In your Mongo shell type command: show dbs . You should see something that resembles the following:

Mongo

In the example above, you can see I have 3 databases: admin, config, and local.

Side Note: If at anytime it’s needed to stop mongo, (shutting down bc you keep getting an error message that address is already in use, the terminal command is: brew services stop mongodb-community )

Install MongoDB Compass

Download the OSX download for MongoDB Compass here. Follow the directed steps to install Compass in your Applications folder. Open the application. This is an example of what Compass will look like when it’s connected to the database:

MongoDB Compass

Connect MongoDB with Node.js

In desired file path, create a new folder: mkdir mongo-demo . Cd into this new folder and run: npm init — — yes. Install Mongoose to work with MongoDB: npm i mongoose . Open app in desired text editor. Create new file: touch index.js .

Set up connection through Mongoose to MongoDB with connection string. This connection string will change when in production environment and will not be hardcoded, it will come from config file. You’ll notice on line 3 the string writes to a ‘playground’ db, but we haven’t created that database yet. MongoDB auto creates the db the first time we write to it.

index.js

When you run nodemon index.js in your terminal, a connected MongoDB will show like the following:

Mongoose Schema

A schema defines the shape of documents within a collection in MongoDB¹.

Schema Data Types:

  • String
  • Number
  • Date
  • Buffer (stores binary values)
  • Boolean
  • ObjectID (unique identifiers)
  • Array
Schema

Models

Object is an instance of a Class(blueprint). To create a Class, need to compile the schema into a Model.

In NoSQL db’s, properties of document can be complex objects, which is not possible in relational database (ex: line 21). There is no need for the many-to-many relationships like in SQL db. NoSQL db’s are also called ‘schemaless’.

Save a Document in MongoDB

In the terminal, when we run our file with node index.js, so the server doesn’t restart each time there are changes to our code:

In the MongoDB Compass application, we can see the database, and the document just created:

MongoDB Compass

Query(Retrieve) Documents

I made a second document before querying the db for all musicians (see below code).

When file is run and the database was queried for all musicians, the output in the console:

Querying the Database

Filter Documents:

Example: Filtering Documents by Name

Complex Queries:

We only had 1 document with name “Phoebe Bridgers”, but if there were more, it would should only the first 10 and sort them by their name.

Comparison Operators

  • eq — equal
  • ne — not equal
  • gt — greater than
  • gte — greater than or equal to
  • lt — less than
  • lte — less than or equal to
  • in
  • nin — not in

Above, I changed the find method in three different ways: (1) I added a bookingPrice attribute and then queried for any bookingPrice greater than ($gt) 9000. (2) I added a bookingPrice attribute and then queried for any bookingPrice greater than ($gt) 9000 and less than or equal to ($lte) 10000. (3) I used the find method to query for bookingPrices that only matched the values in our array.

Logical Query Operators

  • or
  • and

Regular Expressions

Counting

Number of documents instead of documents themselves:

The result value is currently 1

Pagination

Get the documents on a given page:

Setting Up a Seed File

In our main application, set up a new file where we will store our musicians that we will import into the database: touch musician-data.json . The file can be set up like this:

musician-data.json — seed file

In our terminal run the following command to start a new MongoDB database collection and import the above file: mongoimport — — db mongo-musician — — collection musicians — — drop — — file musician-data.json — — jsonArray . There should be spaces before each set of dashes in the command above, this is what the command would correctly be:

If successful, you should see a message that resembles this in your terminal:

MongoDB Compass should resemble this, showing the 5 documents imported:

For reading this database and performing a query on it, our index.js file will now look like this:

And when the code is run, the console should resemble this:

Updating a Document — Query First (Retrieving First)

Updating A Document — Update First

See the list of update operators here.

Deleting / Removing Documents

  1. Node.js Tutorial for Beginners | Programming with Mosh | “https://www.youtube.com/watch?v=TlB_eWDSMt4&t=2349s
  2. MongoDB | “https://docs.mongodb.com/manual/
  3. Installing MongoDB with Homebrew | Stack Overflow | “https://stackoverflow.com/questions/57856809/installing-mongodb-with-homebrew
  4. Install MongoDB Community Edition on macOS | “https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
  5. Installing MongoDB in a MAC . Database — How to use MongoDB. Node JS | “https://www.youtube.com/watch?v=mnKAWCUbjjc

SIDE NOTE: Starting MongoDB.Set up the directory by typing in terminal command

  • brew services start mongodb-community
  • brew services list (To verify that MongoDB is running, you should see the service ‘mongodb-community’ listed as ‘started’ )

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Osha Groetz

Osha Groetz

93 Followers

Software Engineer. A new addict of ReactJS & Javascript, CSS & APIs, with a little dabbling in Ruby, Ruby On Rails…