Can't add more than one exercise in MongoDB (exercise tracker)

this is the code, what can i do about it

const express = require('express')
const app = express()
const cors = require('cors')
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const mongodb = require('mongodb');
const mongoUrl = process.env.MONGO_URI;
app.use(bodyParser.urlencoded({ extended: false }));
  useNewUrlParser: true
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
//create schemas and models 
const exercisesSchema = new mongoose.Schema({
  description: {type: String},
  duration: {type: Number},
  date: { type: Date, default: }

const schema = new mongoose.Schema({
  username: {type: String, required: true }
let Exercises = mongoose.model('Exercises', exercisesSchema);
let User = mongoose.model('User', schema);
//Create a New User'/api/users',(req,res)=>{
const userName= req.body.username;
  //find user in database by name put in username field 
  if(err) console.log(err);
    res.send("Username Is Alerdy Taken")
  }else if(userName!=""){
      const newUser = new User({username: userName});,data)=>{  
        if (err) console.log(err);
          username: data.username,
    //else if username field is empty send 'Path `username` is required.'
     res.send('Path `username` is required.');
//by going on /api/users route using GET method(putting this route on site field) user should get data of all users and their ids
const _id= req.params._id;
User.findById({ _id},(err,data)=>{
  if(err) console.log(err);
  if(! { = new Date();
    res.send("Path `description` is required.");
  }else if(!req.body.duration){
     res.send("Path `duration` is required.");
    const newExercises = new Exercises({
      description: req.body.description,
      duration: Number(req.body.duration),
      date:new Date(
    let username = data.username;,data)=>{
    if(err) console.log(err);
    username: username,
    duration: Number(req.body.duration),
    date:new Date(,
    _id: _id

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)

MongoServerError: E11000 duplicate key error collection: myFirstDatabase.exercises index: id dup key: { _id: “61cdaa9ecdef42ca520e843c” }
at /home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/operations/insert.js:51:33
at /home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection_pool.js:272:25
at handleOperationResult (/home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/sdam/server.js:370:9)
at MessageStream.messageHandler (/home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js:479:9)
at MessageStream.emit (events.js:314:20)
at processIncomingData (/home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/home/runner/boilerplate-project-exercisetracker-1/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at doWrite (_stream_writable.js:403:12)
at writeOrBuffer (_stream_writable.js:387:5)
at MessageStream.Writable.write (_stream_writable.js:318:11) {
index: 0,
code: 11000,
keyPattern: { _id: 1 },
keyValue: { _id: ‘61cdaa9ecdef42ca520e843c’ }

I think you are trying to insert into the db a new element with the same ID as an already existing one. That’s not possible.

The error is pretty clear, you are trying to save a new exercise with an ID that’s equal to an already existing id: 61cdaa9ecdef42ca520e843c

That _id needs to be unique.
Also mongo will add it automatically for you, so there’s no real reason to manually add it yourself:

So, in the above code, considering that you are declaring the _id variable as such

const _id= req.params._id;

You can see that you are not guaranteeing the uniqueness of that value.

Hope this helps :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.