Creating the Data Access Object
Let's learn how to create a data access object (movies) to connect an application to the database.
We'll cover the following...
In this lesson, we’ll implement the movies
data access object to allow our code to access movie(s) from our database.
import express from 'express' const router = express.Router() // get access to express router router.route('/').get((req,res) => res.send('hello world')) export default router
Creating Data Access Objects
In the backend, let’s create a directory called dao
(data access object). In dao
, create the file moviesDAO.js
with the following code:
let moviesexport default class MoviesDAO{static async injectDB(conn){if(movies){return}try{movies = await conn.db(process.env.MOVIEREVIEWS_NS).collection('movies')}catch(e){console.error(`unable to connect in MoviesDAO: ${e}`)}}}
Lines 1–3: The reference to the database is stored in movies
. We then export the class MoviesDAO
, which contains an async method injectDB
. This method is called as soon as the server starts and provides the database reference to movies.
Line 4: If the reference already exists, the execution of the function is stopped.
Lines 7–10: If the reference doesn’t exist, we go ahead and connect to the database process.env.MOVIEREVIEWS_NS
and the movies
collection.
Lines 11–13: If we fail to get the reference, we send an error
message to the console
.
Retrieving movies
We now need to define the method to get all movies from the database. Add the code in the widget below to the moviesDAO.js
file:
static async getMovies({// default filterfilters = null,page = 0,moviesPerPage = 20, // will only get 20 movies at once} = {}){let queryif(filters){if("title" in filters){query = { $text: { $search: filters['title']}}}else if("rated" in filters){query = { "rated": { $eq: filters['rated']}}}}let cursortry{cursor = await movies.find(query).limit(moviesPerPage).skip(moviesPerPage * page)const moviesList = await cursor.toArray()const totalNumMovies = await movies.countDocuments(query)return {moviesList, totalNumMovies}}catch(e){console.error(`Unable to issue find command, ${e}`)return { moviesList: [], totalNumMovies: 0}} }
Lines 1–5: The getMovies
method accepts a ...