Server-based Web Programming
(1DV023, 1DV523)

Persistent data

MongoDB, Mongoose, PRG, Sessions

Licence for this work

This work is produced by Mats Loock for the course Server-based Web Programming (1DV023) at Linnaeus University.

All content in this work excluding photographs, icons, picture of course literature and Linnaeus University logotype and symbol, is licensed under a Creative Commons License
Creative Commons Attribution 4.0 International License.

You are free to

  • copy and redistribute the material in any medium or format
  • spread the whole or parts of the content
  • show the whole or parts of the content publicly and digital
  • convert the content to another format
  • change the content

If you change the content do not use the photographs, icons, picture of the course literature or Linnaeus University logotype and symbol in your new work!

At all times you must give credit to: ”Linnaeus university – Server-based Web Programming (1DV023)” with the link https://coursepress.lnu.se/kurs/serverbaserad-webbprogrammering/ and to the Creative Common-license above.

We will use a database!

  • A database is a collection of data that is organized so it can be easily accessed, manage and updated.
  • Retrieve, add, modify, destroy
    • Query, filter, sort, ...
  • (We can host it ourselves but it's easier to let somebody else do it.)

MongoDB ecosystem

  • MongoDB
    • An open-source document-based database system.
      • “MongoDB” derives from the word “humongous” because of the database’s ability to scale up with ease and hold very large amounts of data.
    • Stores data in flexible, JSON-like documents.
    • The document model is simple to learn and use.
  • MongoDB Atlas
  • Mongoose

Create a MongoDB database

Managing the Mongoose connection

  • You connect to MongoDB with the mongoose.connect() method.
    • The connection string, enforcing access control, can be found at the DaaS provider.
      • mongodb+srv://<dbuser>:<password>@<cluster>.mongodb.net/<name>?retryWrites=true&w=majority
    • Returns a Promise.
  • Listen for connection events.
    • When successfully connected (connected).
    • If the connections throws an error (error).
    • When the connection is disconnected (disconnected).
  • If the Node process ends, close the Mongoose connection.

Converting a schema into a model

  • Convert a schema into a model by passing the schema to mongoose.model(modelName, schema).
  • An instance of a model is called a document.
  • The module (Task.js) resides in the models directory.

CRUD, Verbs, and Actions

  • A route provides a mapping between HTTP verbs and URLs to controller actions.
  • Each action maps to a specific CRUD operation in a database.
  • Route parameters, such as :id above, are named URL segments that are used to capture the values specified at their position.

Routes mapping to the tasks controller

  • The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

Create - the C in CRUD

  • Create a new instance of the model....
  • ...and save the document to the database. Easy peasy!

Read - the R in CRUD

  • Use find, and pass an empty object, to find all documents in a collection.
  • It's good practice to transform the documents into anonymous objects before passing the data to the view.

Update - the U in CRUD

  • Use updateOne to update a document in the database.

Delete - the D in CRUD

  • Use deleteOne to remove the document that matches the condition.

The web server does not have a clue about the state

  • Neither the server nor the browser has an intrinsic way of knowing that it is the same browser that visits the same site.
    • (How is it then possible to log on to something?)

Maintain the state with sessions

  • A session cookie contains a session ID, a unique identifier used to index the server's session storage.

Managing session i Express

  • The default server-side session storage is MemoryStorage.
    • Not for production.
    • Sufficient for development and testing needs.
  • Just the session ID is stored in the cookie itself.

How to prevent duplicate form submissions?

  • "Double posting" occurs when the user refreshes the server response of an HTTP POST request.

Post/Redirect/Get (PRG)

  • To avoid "double posting" return a redirect command instead of a view directly.

What is a flash messages?

  • To avoid "double posting" it's common to use the Post/Redirect/Get pattern (PRG).
    • How do we keep the user posted after the round trip?
  • Whenever you redirect someone on your website it is a good idea to use a flash message to let them know that what they just did worked or not.
    • The flash message should survive only a round trip.
    • Use a session variable to save the message and delete the message on the next request.

Implementing PRG and flash messages

  1. In the function handling the POST request, create a flash message before the redirect.
  2. Before the routing be sure to transfer the data of session variable flash to the response object.
  3. Delete the flash session variable.
  4. View the flash message.
  5. Done! Easy peasy!