What the CRUD (with Mongo)
This week, I’ve been getting familiar with Mongo, a non-relational database. As will all databases, the things that I were interested in included CRUD which stand for Create, Read, Update, and Delete.
So we’ll learn to append information, get information, replace existing information, and completely delete a file. So let’s get started!
Let’s get started with installing MongoDB and Robo T3. Mongo is an open source database that will provide us with a NoSQL database and RoboT3 is a GUI that will help us visualize the data inside of our database. This will make it easy for us to see how we manipulate our database!
After unzipping the file for MongoDB, I recommend doing two things.
- Rename the file as mongo
- Create another file called mongo-db
The reason you’d want to rename it is for understandability. The file will come with commands that you’ll be able to use to initialize your database. The secondary file, mongo-db, will hold the database itself. This is better than writing into your hard drive, which is the default, because you’ll run into a lot of permission requests.
Great, let’s also install Robo T3. I’ve personally put this application on my desktop but you can put it wherever you’d like.
So now, to start up your mongo database you’ll need to access the directory to mongo where those commands are being stored and the path to where we’re storing our database or mongo-db. So below you’ll see the command line that I enter to initialize my database, you should adjust yours accordingly.
/Users/johnsonkow/mongodb/bin/mongod
--dbpath=/Users/johnsonkow/mongodb-data
From there you will see an output that shows ‘listening’ and by default it’s 27017. Back on Robot T3, you can connect to that port! If any of these instruction seem confusing or completely off, I invite you to look at the documentation for both.
At this point, you’re set up to start creating code for a simple app to create those CRUD methods.
I created a file called “task manager” which is the name of the app I’m interested in creating but you can call it whatever you’d like. Now, we’ll need to install the mongo library for node to connect to our database. This will provide us with functions to connect with our database and access unique identifiers.
const {MongClient, ObjectID} = require('mongodb')
const connectionURL = 'mongodb://127.0.0.1:27017';
const databaseName = 'task-manager'
We’ll need the url and database name as well to start interacting with our database.
MongoClient.connect(connectionURL, {useNewUrlParser: true}, (error, client) =>{if(error){return console.log('Unable to connect to database')}const db = client.db('task-manager')
)
First thing we’ll do is write the code above. MongoClient is a Node library that helps to connect and interact with the Mongo database. We provide the URL, configuration, and a callback function. The callback function takes an error and client because we’d like to know if our connection is successful or not. The if statement will run and stop the code if an error exists. If not, we can have successfully connected to our database. Const db will be the database of interest.
For all CRUD operations, we will be able to do them for one specific item in a collection or to multiple. For these examples, I’ll alternate between the two.
Create
db.collection('users').insertOne({ name:'Min', age: 21}, (error, result)=>{ if(error){ return console.log('Unable to insert user')}
Immediately after creating our constant ‘db’, we’ll start writing our code for CRUD.
We access our database and connect to our collection of users. We use insertOne as it takes an object and a callback function as its arguments. The object is the information you’d like to write to the database while the callback is just an error handler. If there’s an error, we’ll write to the console that we didn’t write anything.
If you’d like to put more than one object, you can use the insertMany() function which accepts an array of objects and the same callback function.
READ
db.collection('users').find({ age: 25}).count((error,users)=>{ console.log(users)})
This one looks a bit different and that’s because ‘.find’ returns something called a cursor which is useful because sometimes you’re not necessarily looking for all the information but rather how much information. So for this example, I’m querying my database for the number of all the objects in my users collection that have an age of 25. If you DO want to access all that information, instead of .count you can use .toArray().
If you wanted to search for one particular object, you’d use findOne() and provide a filter in which you specify what you want the object to satisfy. So maybe you’d want to find the user by the name of “Jen”.
Update
db.collection('users').updateOne({ _id: new ObjectID("5fbd38c21f55a04488c3d6f7")},{ $set:{ name:"Mike" }}).then((result)=>{ console.log(result)}).catch((error)=>{ console.log(error)})
To update, we connect to our users collection and use the updateOne method. To specify which object you’d like to update, we provide it the unique identifier which you can get from Robo T3.
The cool thing about the update method is how unique it is compared to the other CRUD methods. You’ll notice that is has an update operator, “$set” that says exactly what you’d like to replace inside of this object with the unique identifier provided.
The other cool thing is that it makes use of promises. When using .then(), you’re essentially saying “when things go right”, and when using .catch() you’re essentially saying “when things go wrong” and you can print both those things.
If you’d like to updateMany, you can just pass a filter as oppose to a unique identifier. This way you’ll change all the objects that satisfy that filter. For example you can say “Update all my users with the age: 25”.
Delete
db.collection('users').deleteMany({ age:25}).then(result => { console.log(result)}).catch(error => { console.log(error)})
Lastly to delete many users you can provide a filter that will be satisfied by many objects that you’ll target. In this case, we’re targeting all users that are 25 years of age. As always, we’ll finish it off with those promises which essentially is our error handler.
If you only want to delete one thing, you’d use the .deleteOne() method and filter by something like the ID or anything else that makes your information unique!
I hope this helps someone out there getting familiar with Node. As always, it has been a pleasure to help anyone that reads these blogs. Happy Coding.