In this lesson, we will explore how to retrieve a specific record from a MongoDB database using Mongoose by its unique ID
. This functionality is crucial for applications where precise data retrieval is required, such as viewing a user's profile or fetching specific details of a product.
In this lesson, you'll learn:
- The importance of unique
IDs
in MongoDB. - How to set up a Mongoose model.
- How to connect to a MongoDB database using Mongoose.
- How to retrieve a record by its ID.
- Basic error handling during data retrieval.
Let's understand what a record ID
is and its role in MongoDB. These IDs are important because they ensure every record can be uniquely identified, akin to a student ID in a school.
JavaScript1const mongoose = require('mongoose'); 2 3const idExample = new mongoose.Types.ObjectId(); 4console.log(idExample);
In this snippet, we create a new MongoDB ObjectId using Mongoose. Each MongoDB ID is a unique 24-character hexadecimal string. This identifier is automatically generated when a new record is inserted into a collection.
Now we'll set up a Mongoose model named Todo
to standardize the structure of our ToDo items, which lays the foundation for data validation and querying. It's helpful because it enables consistent and predictable data storage.
JavaScript1const todoSchema = new mongoose.Schema({ 2 task: { type: String, required: true }, 3 completed: { type: Boolean, default: false } 4}); 5 6const Todo = mongoose.model('Todo', todoSchema);
In this script, we define a schema for Todo
items with task
and completed
fields. The task
field is mandatory, while completed
is optional with a default value of false
. Then, we create a model from this schema using mongoose.model
.
Let's connect our application to a MongoDB database. This is crucial because our application cannot query the database without a proper connection, this is a prerequisite for performing any database operations.
JavaScript1mongoose.connect('mongodb://127.0.0.1:27017/todo-app', { 2 useNewUrlParser: true, 3 useUnifiedTopology: true 4}).then(() => { 5 console.log('Connected to MongoDB'); 6}).catch((error) => { 7 console.error('Connection error', error); 8 process.exit(1); 9});
Here, we establish a connection to a local MongoDB database named todo-app
using the mongoose.connect
method. We set useNewUrlParser
and useUnifiedTopology
options to avoid deprecation warnings. Successfully connected messages are logged, and in case of errors, the process exits.
Now we'll write the code to retrieve a single ToDo item by its unique ID
, which is a fundamental task in data retrieval processes. This is helpful for quickly accessing specific records within our application.
JavaScript1app.get('/todos/:id', async (req, res) => { 2 const { id } = req.params; 3 4 try { 5 const todo = await Todo.findById(id); 6 if (!todo) return res.status(404).json({ message: 'Todo not found' }); 7 res.json(todo); 8 } catch (error) { 9 res.status(500).json({ message: 'Failed to load todo' }); 10 } 11});
In this code, we define a route to get a single ToDo by its ID
. When a GET request is made to /todos/:id
, the id
parameter is extracted from req.params
. req.params
is an object containing properties mapped to the named route parameters, which allows us to access the parameters of the route. The Todo.findById
method is used to retrieve the item. If the item isn't found, a 404 response is returned. If an error occurs, a 500 status with an error message is sent.
In this lesson, we've learned how to retrieve a single record by its ID
using Mongoose. We started by understanding the importance of unique IDs, set up a Mongoose model, connected to a MongoDB database, retrieved a specific record, and handled potential errors. This foundational knowledge is essential for precise data manipulation within any MongoDB-backed application.