Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Persisting Express sessions through MongoDB and mongo-connect

From: Node.js Essential Training

Video: Persisting Express sessions through MongoDB and mongo-connect

For many web applications, establishing a session is a crucial way of identifying a user. Sessions make it possible for people to log into a website and not have to re-enter their password on every page. In this video we will add sessions for our application and use them to track a simple piece of data. First let's go to the exercise files. Go to chapter seven, video four. And then copy the start folder to the desktop. Now go to terminal and change directory to that start folder. I'm just going to drag it in to get the path.

Persisting Express sessions through MongoDB and mongo-connect

For many web applications, establishing a session is a crucial way of identifying a user. Sessions make it possible for people to log into a website and not have to re-enter their password on every page. In this video we will add sessions for our application and use them to track a simple piece of data. First let's go to the exercise files. Go to chapter seven, video four. And then copy the start folder to the desktop. Now go to terminal and change directory to that start folder. I'm just going to drag it in to get the path.

And then finally type NPM install, and then press Return. Now in certain environments and frameworks, session storage is handled for you. Consequently, you can end up taking them for granted. When I first started writing express applications, I quickly discovered sessions are now my responsibility. Not only did I have to turn them on, I also had to figure out a way of storing them. While you can just let express store the session information in memory, there are some down sides this approach. First if you are running your application on multiple processes, the session will only be available in the process where it was started.

If you have a load balancer in front of your web application and the user gets sent to another process, their session will suddenly disappear. Another disadvantage is that if your server has to be restarted, all of the sessions are lost and have to be reestablished. A final disadvantage is that your sessions storage space is limited by the amount of memory you have set aside for your application. Now this may not be such a big deal if you manage your own server and you give your application loads of memory. But it may become an issue if you're running the application on a cloud surface where you're paying for memory incrementally.

An overall better approach is to store your sessions in a central location, such as a MongoDB Database. Fortunately there's Middleware available that will tie your Express sessions to a MongoDB Database. It's called Connect Mongo. Express is written on top of a smaller framework called Connect, so this Middleware is also compatible with Connect. Let's install it now. I'm going to type npm install and then --save, and then connect- mongo. If you see a warning on this line, disregard it.

Now that we've installed connect-mongo, let's add it to the application. I'm going to open up the start folder in sublime text, and then I'm going to go to app.js. Just like any other module, we're going to require connect mongo. We're going to store it in a variable called Mongostore. Now before ending this line we're going to pass express into connect Mongo. Next, let's set up express to use sessions. Go to the line just before express.body parser, and make some space.

We're going to add another app.use call here. The first thing we're going to add is the cookie parser. This line is crucial because this is the software that's going to read the cookies that the browser's sending to the server. Now let's set up the sessions. Again, we're using apt.use. Now we're going to call express.session. This function takes an object as an argument. And this object is going to configure the sessions. First, we're going to type in a secret. Typically, you want to add a randomized string here.

The secret is going to be used to encrypt the session information. You can just leave the string keyboard cat here or you can have your cat actually walk on the keyboard to generate a randomized string. And then the other property we're going to define is the store property. This is going to tell express where we want to store our sessions. So on line eight, we defined Mongostore, and that's where we're going to store the sessions. So let's declare a new Mongostore instance. That constructor takes an object as well.

We need to set one property here for mongoose_connection. Now this file doesn't currently have a database connection available. But we can pass it in. So for the moment let's type in db. Now let's go up to line six and add db as another argument. Save this file, and now let's go to server.js. We're requiring the db on line three and now we can pass it in on line four. So now, sessions are available in our Express application and they're going to be stored in the MongoDB database.

However, we need to actually do something with the sessions. Let's track the last flight that someone viewed and display it on the list of all the arrivals. To do that, let's go to the routes. Go to index.js, and then go to the flight function. And then using the data that we already have here, we can set the session information. On the request object there is a new property called session. This session property is an object, and we can set the properties of this session object to whatever we want.

So in this case, I'm going to set lastNumber, and then I'm going to set that property to number. Now let's go to the arrivals handler. We're currently just passing the arrivals into the Jade view. However, we could also pass in the last viewed flight. Let's do that by adding it here. And again, we're going to get that data out of the session. The session is always stored in the request. Now let's go to our Jade view and adjust it. I'm going to add a paragraph tag here and I'm going to use the last number variable.

But let's concatenate this string here. So now whenever we go the arrivals page, it'll show us which flight was the last one viewed and it's going to show it to us in a paragraph tag. Now let's start up the server and test all this. Go to terminal and type node space server and then press return. It looks like we have an extra semicolon in app.js. Let's go there now and fix this. Since we're calling express.session, within an argument to another function, we don't need a semicolon.

Remove it and then save the file, and let's try this again. Press the up arrow on your keyboard, and then, press return. So now the server is listening on port 3000. Let's load up one of the flights. Go to local host at port 3000 and let's go to flight 33. Now let's go to the arrivals page. I'm going to open it up in a separate tab. And it's now showing that the last flight we viewed was 33. Let's go to flight 18. Another thing to note, is that this is specific session information.

Other people going to this website are not going to see this information. Let's open up a session free window. Go to file and new incognito window, and then paste in the arrivals URL. You'll notice here that it says the last flight viewed is undefined. That's because the session is in this browser window, and not in the session free window. The connect Mongo middleware makes it easy to store all of your express sessions in MongoDB. Once you've enabled sessions, variables can be set as a request object and persisted from request to request for that user.

In the next video, we'll add a login form and use sessions to keep users logged in.

Show transcript

This video is part of

Image for Node.js Essential Training
Node.js Essential Training

52 video lessons · 12312 viewers

Joseph LeBlanc
Author

 
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

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

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.


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.

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
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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.