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 }));
require('dotenv').config()
mongoose.connect(mongoUrl,{
  useNewUrlParser: true
})
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});
//create schemas and models 
const exercisesSchema = new mongoose.Schema({
  _id:{type:String},
  description: {type: String},
  duration: {type: Number},
  date: { type: Date, default: Date.now }
});

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
app.post('/api/users',(req,res)=>{
const userName= req.body.username;
  //find user in database by name put in username field 
User.findOne({username:userName},(err,foundOne)=>{
  if(err) console.log(err);
  if(foundOne){
    res.send("Username Is Alerdy Taken")
  }else if(userName!=""){
      const newUser = new User({username: userName});
        newUser.save((err,data)=>{  
        if (err) console.log(err);
        res.json({
          username: data.username,
          _id: data.id
        })
      })
    //else if username field is empty send 'Path `username` is required.'
    }else{
     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
app.get('/api/users',(req,res)=>{
  User.find({},(err,data)=>{
   res.json(data);
  })
})
app.post('/api/users/:_id/exercises',(req,res)=>{
const _id= req.params._id;
User.findById({ _id},(err,data)=>{
  if(err) console.log(err);
  if(!req.body.date) {
      req.body.date = new Date();
    }
 if(!req.body.description){
    res.send("Path `description` is required.");
  }else if(!req.body.duration){
     res.send("Path `duration` is required.");
  }else{
    const newExercises = new Exercises({
      _id:_id,
      description: req.body.description,
      duration: Number(req.body.duration),
      date:new Date(req.body.date).toDateString()
    });
    let username = data.username;
    newExercises.save((err,data)=>{
    if(err) console.log(err);
    res.json({
    username: username,
    description:req.body.description,
    duration: Number(req.body.duration),
    date:new Date(req.body.date).toDateString(),
    _id: _id
    })
    })
  }
})
})


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

error:
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: https://docs.mongodb.com/manual/indexes/#default-_id-index

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.