Implement Retrieve User by ID

Sometimes the frontend needs a specific user instead of the entire collection.

Mongoose provides findById() for retrieving a document using its MongoDB identifier.

However, malformed MongoDB ObjectIds can cause casting errors. We should validate the ID before querying the database.

Get User by ID Service
export async function getUserById(userId) {
  return User.findById(userId)
    .select('-password');
}

Finds one user document using its MongoDB ObjectId and excludes the password field.

Key Takeaways
  • findById() retrieves a document using its identifier.

  • Validate ObjectIds before querying.

  • Return 404 when a valid identifier does not match a document.