Retrieving a Single Record by ID

Retrieving a Single Record by ID

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.

What You'll Learn

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.

Step 1: Understanding Record IDs

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.

const mongoose = require('mongoose');

const idExample = new mongoose.Types.ObjectId();
console.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.

Step 2: Setting Up Your Mongoose Model

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.

const todoSchema = new mongoose.Schema({
    task: { type: String, required: true },
    completed: { type: Boolean, default: false }
});

const 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.

Step 3: Connecting to Your Database

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.

mongoose.connect('mongodb://127.0.0.1:27017/todo-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Connected to MongoDB');
}).catch((error) => {
    console.error('Connection error', error);
    process.exit(1);
});

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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal