DEV Community

Cover image for A difficult backend problem I had to solve
Hadiza Mohammed
Hadiza Mohammed

Posted on

A difficult backend problem I had to solve

Hey everyone! I recently faced a challenging backend problem while working on a project for my FreeCodeCamp certification. I want to share how I tackled it and why I'm excited about joining the HNG Internship.

The Challenge: Associating Exercises with Users

I was building an API that lets users create accounts, add exercises, and view their exercise logs. The tricky part was ensuring each exercise was correctly linked to the right user without creating duplicate data.

The Solution

1. Designing the Database Schema

I used MongoDB with Mongoose, creating separate schemas for users and exercises. The exercise schema included a reference to the user's ID, establishing a relationship between them.

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true }
});

const exerciseSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  description: { type: String, required: true },
  duration: { type: Number, required: true },
  date: { type: Date, required: true }
});
Enter fullscreen mode Exit fullscreen mode

2. Implementing the Endpoint

Next, I created an endpoint to add exercises. It checked if the user existed, then added the exercise, linking it to the user.

app.post('/api/users/:_id/exercises', (req, res) => {
  const userId = req.params._id;
  const { description, duration, date } = req.body;
  const exerciseDate = date ? new Date(date) : new Date();

  User.findById(userId, (err, user) => {
    if (err || !user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const newExercise = new Exercise({
      userId: user._id,
      description,
      duration,
      date: exerciseDate
    });

    newExercise.save((err, exercise) => {
      if (err) {
        return res.status(500).json({ error: 'Failed to add exercise' });
      }

      res.json({
        username: user.username,
        description: exercise.description,
        duration: exercise.duration,
        date: exercise.date.toDateString(),
        _id: user._id
      });
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Reflecting on the Experience

This project taught me a lot about managing database relationships and handling asynchronous operations in NodeJS. It was a challenging but rewarding experience that boosted my confidence as a backend developer.

Joining the HNG Internship

I’m super excited about the HNG Internship. It’s a fantastic opportunity to work on real-world projects, learn from experienced developers, and improve my skills. If you’re curious about the program, check out the internship page and their premium offerings.

Conclusion

Backend development can be tough, but solving these problems is incredibly fulfilling. I can’t wait to continue this journey with the HNG Internship and tackle even more exciting challenges. Thanks for reading, and I hope my experience inspires you to embrace the challenges you face in your development journey!

Top comments (0)