Complete Intro to Databases

Connect & Query with MongoDB & Express

Brian Holt

Brian Holt

SQLite Cloud
Complete Intro to Databases

Check out a free preview of the full Complete Intro to Databases course

The "Connect & Query with MongoDB & Express" Lesson is part of the full, Complete Intro to Databases course featured in this preview video. Here's what you'd learn in this lesson:

Brian demonstrates how to use Mongoose and Express to connect to the MongoDB database, and how to query the database using the Node.js application started in the previous segment.

Preview
Close

Transcript from the "Connect & Query with MongoDB & Express" Lesson

[00:00:00]
>> So let's open our server.js. And here we're gonna write a little bit of node code const express = require('express'). const { MongoClient } = require('mongodb'). Notice that we have these curly braces here cuz we're gonna be pulling out the Mongo client from Mongodb. We're gonna have a connection string of some variety.

[00:00:41]
Normally, you wouldn't just hard code this in here, you'd get it passed in from like processed at env. So you'd have like, process.env.Mongo connection string and then you'd use like an environmental variable to pass it in, then you'd have something like. As your Key Vault or whatever the Hash core one is called I can't remember the time ahead key might be called Key Vault as well.

[00:01:06]
Anyone something similar like that you'd have some sort of like secret manager that would be managing that. We're not writing this for the cloud at the moment. So we're just gonna put here Mongodb://localhost27017. That's the default connection string for Mongodb. This is the Mongodb protocol that's different from HTTP, right?

[00:01:35]
Local host is your local computer and 27017 is the default port that Mongodb runs on. And if you remember, we expose that through Docker to our local computer. Okay. I'm gonna write an async init function. This is just kind of a habit of mine. I don't even know if this needs to be async.

[00:01:53]
I just always do it this way. And then I'll just write init down here. So I create an async function and then I immediately call it. First thing I'll do is I'll get a client. First thing I wanna do here is I want to indent using spaces and use two cuz this is bothering me.

[00:02:13]
Here we go. So const client = new MongoClient, you can give it the connection string. And then they have to do something here is say use unified topology. It will still work if you don't provide this but it's just saying, Hey Mongodb use your new way of discovering servers.

[00:02:40]
They just require that now or it gives you a big warning eventually I think it'll break. So just say use unified topology true. And then underneath that you're gonna say await client.connect. This will actually go out and connect to Mongo from your Node server. Okay, we wanna create an express app, after this const express = app.

[00:03:06]
And then we're gonna do an app.get. This is the typical express server stuff. So whenever someone calls get, if you remember that's the API that we defined previously, we want them to call this async function that takes in (req, res) If this, express service stuff is looking unfamiliar to you, don't sweat it.

[00:03:33]
This, the point of this course is not the express part. The point of this stuff is how to interact with Mongo in a programmatic setting. And again, go watch some of the note courses in front of masters and they'll help you out with this kind of stuff. So the first thing you want to do here is now we're actually going to get into our real Mongodb stuff.

[00:03:54]
So we're gonna say const db = await client.db adoption or whatever you code your database, right? The whole database. I called my adoption, if you remember, so we're gonna do that. This db objects, you can see his actually of type db. I think it's exactly the same db objects that you get inside of our, a little shell here, right.

[00:04:22]
So if I come in over here and say. This one right db. It's going to be this same db objects. It's gonna have the same similar sorts of methods. Okay, and then we're going to grab a collection. So we're going to say const collection = db.collection('pets') cuz that's what we called our collection.

[00:04:49]
So now I have this collection object that has a bunch of methods that I can actually use to run queries. So I'm gonna say const pets = await collection.find, right? So we're gonna do that find method. We wanna do the $text, again these queries are gonna look very similar to you.

[00:05:21]
$text. And inside of that, we're gonna have another object which is gonna be $search, and it's going to be req.query.search, right? That's gonna be what comes in with the query string. And then we're gonna tell it, please don't provide the ID. So we're gonna use projection to omit the ID because we don't want that This got really messy quickly.

[00:06:06]
There we go. All right, so assume you find, it's gonna go find the whatever texts that we searched for inside of our search box, we're gonna omit the ID. The next thing that we're gonna do is we're gonna put in a sort. So .sort and we're gonna sort by score if you remember how we did that.

[00:06:27]
So score colon, another object and the dollar sign meta, and we're gonna do tech score. Okay, we only want 10. So we're gonna say .limit 10. And then here, remember it gives you back an iterator. That's actually not what we want this time. We just want the whole thing.

[00:06:50]
So we're gonna say .toArray. Now what's really interesting about this is until we call toArray here. But stop that, you can see here that toArray here gets back a promise. That's actually what invokes the query. Like you need some sort of like final action that says, all right, I'm going to be.

[00:07:11]
I've constructed all this stuff go get it. So toarray is one of those methods there's other ones, but if you notice your like limit, for example, it's still a cursor. You're still building your query. So for example, I think you can call next here. So next would actually give you the first bit of whatever that cursor has to give.

[00:07:35]
Because we're calling toArray, toArray says give me everything that matches this, but we've limited to 10 so it's not that much. So now pets, if you look at this, it's going to be an array of stuff that our Mongo array or that Mongo gave back to us. So here we can say res.json, status: "ok".

[00:07:58]
And then we can say, pets pets, or if you remember JavaScript, you can just say pets and that'll be the same thing as pets:pets. And then you have to say .end, and that'll send back the API response from get. That's it. I mean that's the entirety of writing Mongo queries for Node.js.

[00:08:22]
Couple more things, but in here, you have to give it a port. So I'm gonna say const PORT. I'm just gonna give it 3000. I'm gonna say app.useexpress.static./static. So this will serve our index.html. If we put CSS files in there, that would work as well. But that's what this is doing is hey, everything inside of my static directory serve statically.

[00:08:50]
App.listen(PORT). This will start it listening on localhost 3000. And just to remind yourself cuz l can never remember. I'm gonna say, running on http://localhost, port. That's it. That's our whole application. So I'm gonna open my terminal here. And I'm gonna say, node server.js. App is not defined. So let's see what I missed here.

[00:09:39]
Did I forget to? I did this the opposite way, app = express. So I changed line 12 here. You wanted line 12 here to say const app = express. Not the other way around. I messed that up. Okay, let's try that again. There we go, running on localhost 3000.

[00:10:06]
So now I should be able to open this in my browser here. Got a nice little search bar here. So let's say luna havanese. And you can see here it is returning stuff out of our database. Or I could say reptile fido. Fido, reptile, Or I don't know, cat african gray.

[00:10:43]
There you go. Again, this is the most basic thing that you could ever write for a Node application querying Mongo. But now you can kind of see here's how you kind of get it into your application and start writing queries. So I mean, something fun you could do here is you can go make like a searchable Mongo database has like search facets, right?

[00:11:06]
This is not an ideal experience for searching around a database. It'd be better if you could say like, lists cats, reptiles birds and make like a better more full fledged application out of it if you wanted to learn a bit more.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now