Exercise Tracker: _id in schemas

In the Exercise Tracker project the instructions show three structures, all with the same username and _id. According to the mongoose documentation " By default, Mongoose adds an _id property to your schemas". I’m confused therefore by the three structures all having the same _id.

I have two questions

  1. if mongoose is handling them automatically, wouldn’t they be different?
  2. I assume therefore that I should manually handle the _id myself . Am I correct?

Not necessarily. These are all for the same user and that is the user’s _id.

No. Don’t do that. Let your MongoDB handle it.

Thank you for replying.

I have the following thoughts/questions, if I let MongoDB handle it.

I create a user called Alan. MongoDB ‘creates’ a _id of A123 as an example.

I then create another user called Jeremy. MongoDB ‘creates’ a _id of J456 as an example.

I then create an exercise for Alan.

  1. why would MongoDB ‘create’ a _id of A123?
  2. might it not be E789
  3. why not J456?

From the test descriptions:

  1. The returned response from POST /api/users with form data username will be an object with username and _id properties.
  2. The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.
  3. A GET request to /api/users/:_id/logs will return the user object with a log array of all the exercises added.

You’re always returning the user _id. There’s no mention or requirement of an _id field for the exercises.

I’m not sure what you’re asking here. Every document in a MongoDB has a unique _id. You may or may not keep the users and exercises in separate collections, so the exercise records may not have an _id according to your implementation (they won’t if they’re stored in an array on the user document and they will if they are stored in a separate collection).

You really don’t care what the _id is as long as it’s unique, so let MongoDB handle it and it will be unique, even across different collections. If you’re curious about the implementation, just google ‘mongodb objectid.’

Thank you so much for replying - your answer makes sense to me and I understand what’s needed now :slightly_smiling_face:.