Creating the Data Access Object
Explore how to implement a data access object for movies in a Node.js backend using MongoDB. Learn to connect to the database, query movies with filters, and manage pagination efficiently. This lesson teaches you to structure backend code for reliable data retrieval in a MERN stack application.
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 routerCreating 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:
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:
Lines 1–5: The getMovies method accepts a filters object as its first argument and retrieves results on page ...