Start learning with our library of video tutorials taught by experts. Get started

Node.js Essential Training
Illustration by Richard Downs

Querying MongoDB collections


From:

Node.js Essential Training

with Joseph LeBlanc

Video: Querying MongoDB collections

Once documents are entered into a Mongo DB collection, you can query them to display the data. Mongoose has functions for querying Mongo DB collections and handling the responses. In this video, we'll query the flights collection and display the results in a view. Lets go to the exercise files. Go to chapter seven, video three and then copy the start folder to your desktop. Next, let's install the dependencies. Change directory to that start folder and then type in npm install.
Expand all | Collapse all
  1. 3m 9s
    1. Welcome
      42s
    2. What you should know before watching this course
      57s
    3. Using the exercise files
      47s
    4. Using the challenges
      43s
  2. 18m 50s
    1. Why use Node.js?
      2m 1s
    2. Choosing a Node.js installation process
      4m 56s
    3. Installing Node.js on the Mac
      2m 5s
    4. Installing Node.js on Windows
      1m 43s
    5. Installing Node.js via Node Version Manager on Ubuntu Linux
      4m 45s
    6. Installing Node.js via Node Version Manager on a Mac
      3m 20s
  3. 13m 54s
    1. Exploring language additions to the V8 JavaScript engine
      3m 38s
    2. Understanding require() and modules
      6m 39s
    3. Understanding callback execution in the event loop
      3m 37s
  4. 12m 23s
    1. Initializing Node.js projects
      2m 37s
    2. Finding an NPM
      3m 30s
    3. Maintaining projects using the npm command
      6m 16s
  5. 21m 4s
    1. Creating modules with getters and setters
      6m 33s
    2. Understanding module caching and scopes
      6m 15s
    3. Implementing JavaScript creational patterns
      5m 8s
    4. Challenge: Leveraging module caching
      55s
    5. Solution: Leveraging module caching
      2m 13s
  6. 32m 27s
    1. Starting Express applications
      3m 42s
    2. Handling GET requests returning JSON
      3m 26s
    3. Navigating large datasets using request variables in routes
      5m 4s
    4. Modifying data through PUT requests
      4m 32s
    5. Supplying middleware to modify HTTP response headers
      4m 37s
    6. Generating HTML views in Jade
      8m 9s
    7. Challenge: List all records as JSON
      37s
    8. Solution: List all records as JSON
      2m 20s
  7. 25m 37s
    1. Evaluating unit testing methodologies
      3m 8s
    2. Isolating existing code for testing
      6m 47s
    3. Supplying helpers for test data
      2m 35s
    4. Writing unit tests with Mocha
      6m 5s
    5. Simulating HTTP requests with SuperTest
      7m 2s
  8. 28m 45s
    1. Connecting to MongoDB via Mongoose
      4m 16s
    2. Defining schemas for collections in Mongoose
      3m 47s
    3. Querying MongoDB collections
      5m 32s
    4. Persisting Express sessions through MongoDB and mongo-connect
      7m 6s
    5. Logging in to Express applications using Passport
      8m 4s
  9. 21m 47s
    1. Controlling the built-in REPL
      4m 18s
    2. Constructing a custom REPL
      5m 40s
    3. Receiving command-line arguments with Optimist
      6m 14s
    4. Building command-line tools
      3m 35s
    5. Challenge: Launch a custom REPL from a command
      41s
    6. Solution: Launch a custom REPL from a command
      1m 19s
  10. 15m 46s
    1. Emitting events and attaching listeners
      5m 32s
    2. Streaming chunked data through readable streams
      2m 33s
    3. Controlling readable streams
      1m 52s
    4. Piping readable data into writable streams
      2m 10s
    5. Handling duplex streams over TCP
      3m 39s
  11. 4m 6s
    1. Deploying projects to cloud hosting services
      2m 36s
    2. Finding Node.js resources
      1m 30s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Node.js Essential Training
3h 17m Intermediate Oct 16, 2013

Viewers: in countries Watching now:

Node.js is a powerful tool for controlling web servers, building applications, and creating event-driven programming. And it brings JavaScript—a language familiar to all web developers—into an environment independent of web browsers. Learn all about Node.js and start creating JavaScript applications in this course with Joseph LeBlanc. He shows how to install Node.js on Mac, Windows, and Linux and dives deep into its modules and Express framework for app development. Learn how to unit test your code, start sessions on web servers, stream data, and create simple command-line tools.

Topics include:
  • Why use Node.js?
  • Installing Node.js
  • Understanding the event loop
  • Initializing Node.js projects
  • Creating modules with getters and setters
  • Starting Express applications
  • Testing your code
  • Working with sessions and databases
  • Building command-line tools
  • Emitting events and attaching listeners
  • Controlling readable streams
Subjects:
Developer Servers Cloud Computing Programming Languages
Software:
JavaScript Node.js
Author:
Joseph LeBlanc

Querying MongoDB collections

Once documents are entered into a Mongo DB collection, you can query them to display the data. Mongoose has functions for querying Mongo DB collections and handling the responses. In this video, we'll query the flights collection and display the results in a view. Lets go to the exercise files. Go to chapter seven, video three and then copy the start folder to your desktop. Next, let's install the dependencies. Change directory to that start folder and then type in npm install.

Then press Return. Now let's go to the code. Open the start folder in sublime text or any other text editor you prefer. Let's go to the routes index.js file. Let's create a new route handler called arrivals. Just like all the other route handlers, it's a function that accepts the request object and the response object as the two arguments. Now from the previous video, we included the flight schema from the schemas folders. We can use this flight schema to also query the mongo database.

The FlightSchema object is a chainable object. We can build up our query with different methods and then execute it. So let's do that now. Start by typing in FlightSchema and then call the find method. We could leave this query just as it is. This would pull in all the documents from the Flights collection regardless of the ordering. One thing though, we actually want the ordering to sort by the Actual Arrive field. So to do that, let's call the Set Options method. The Set Options method takes an object as the argument.

This argument allows us to set the different options for the query. So the one that we want to set is Sort. And in this case, we want to sort by the field Actual Arrive. Now finally, let's execute this query. We can do that by calling the exec function. The exec function takes a function as an argument. And then, this function is provided with an error and the record set as two arguments. I'm just going to call the results, arrivals. First, we want to make sure that there were no errors when we did this query. So first, check the error object.

If there's an error, we want to log it to the console, and then we also want it to tell the browser that there was an error. However, if there was no error, we want to render the results. The first argument is the name of the jade view that we want to render. We're going to be adding a new jade view called arrivals, so let's add that here. And then the second argument is the data that we want to pass to that view. We want to set the title of the page, so set title to arrivals. And then finally, we also want to set the arrivals themselves. Now, let's create the jade view for these arrivals.

Go to the Views folder and create a new view. I'm going to name this arrivals.jade. Let's review list.jade. On line one, there's extends layout and that's going to pull in layout.jade. Then on line three, there's block content. This is defining the content that's going to appear in layout.jade where we have block content defined. So let's build a rivals.jade in a similar way. Lists.jade is displaying flight information in a loop.

And we're going to do almost the exact same thing on the arrivals page. So, let's copy this code and paste it into arrivals.jade. Now let's begin making some adjustments so that we'd see the arrivals information. First, the name of the variable we're passing in as arrivals. Instead of dealing with our standard flight objects, we're dealing with data that's come back from mongo DB. So, we don't have to call get information. However, we do have dates that are in a very long numerical time stamp. Those aren't very user friendly, so let's change those.

I'm going to create a variable here named landed. And I'm going to set that variable to a new date object. This new date object is going to take the actual arrive property and use that to create a formatted date. And now let's replace destination with landed. There's one last piece we need to add before we start the server. And that's the route. Go to app.js and then scroll down. Let's create a new route called arrivals. And then we'll use the arrivals function, that we just defined in index.js of routes.

Now let's start the server, go to terminal and type node server. Then press return. Now lets load up the arrivals route. Go to logo host at port 3000 slash arrivals. Currently we have flights 33 and 18 marked as arrived. Lets find some other flights that we can mark as arrived as well. Go to data index dot js. Lets mark flight 71 as also arrived. I'm going to go to postman, and I'm now going to mark flight 71 as arrived.

And when I do that and hit refresh, it appears in the list. Also, we can stop and restart the server, and this data will still be there. Press Control > C to stop the server. Then press up on the keyboard to bring up node server, and then press return to start the server again. Now go back to the browser and hit refresh. All three records are still there. After creating a schema with Mongoose, you can chain calls to it to query a collection. Once the results come back from Mongo DB, you can then render them in a jade view, or use them however you wish.

The data stays in Mongo DB regardless of how many times you restart your server. In the next video, we'll use Mongo DB to restore sessions.

There are currently no FAQs about Node.js Essential Training.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Node.js Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked