Create a movie reviews app with Node.js and Express
Part 8 - Querying the database using the find() and findOne() queries
Build web apps with NodeJS & Express
🕑 This lesson will take about 10 minutes
So far, you have used the create(), findById, and find() queries. In this lesson, we will look at how you can edit queries to customise the data you want to fetch from the database.
findOne() function with parameters
On the home page, you used the Movie.find() function to find and display all movies that exist in the database. You could create a separate page for different genres or movies released in different years. To do this, you can add parameters to the Movie.find() function, for example, the following code will fetch all action movies from 2023:
findOne() function
Let’s say you just want to fetch a single result that matches your criteria. For example, if you had a database of user profiles, and you wanted to find a user account that matches a provided username and password combination, you could use code like this using the findOne() query:
findOneAndUpdate() function
Let’s say you want to find a record in the database matching some criteria, and then update that record with some new data. In this example, we are fetching a user that matches a given username and existing password, then we update the password with a new password using the findOneAndUpdate() function:
To find more types of database queries and examples, visit the Mongoose documentation.
Challenges
Now that you’ve built a basic working app that can connect to a database, try adding the following features:
a login system where only admins can enter new movie details
a login system where users can save their favourite movies
or a moderation system for adding new movies
the ability to add comments or multiple reviews for a movie
a form where the admin can edit movie details.