'MongoServerError: E11000 duplicate key error collection:

In my database i have two collection-

  1. student collection
  2. student_course_completion collection i want add in bot database.

here is my code-

const file=req.files.file;
  const data=req.body.data;
  const newImg=file;
  const encImg=newImg.toString('base64');
  
  const image={
    contentType: file.mimetype,
    img: encImg,
    size: file.size
  }

  const dataObj=JSON.parse(data);
  dataObj.img=image;
  students_collection.insertOne(dataObj)
    .then(result=>{
      if(result.acknowledged===true){
        const st_course_comlepetion_info=util.cseCourses;
        st_course_comlepetion_info.stid=dataObj.id;
        stCourseCompetion_collection.insertOne(st_course_comlepetion_info)
        .then(result=>{
          if(result.acknowledged){ res.send(true);}
        })
        .catch(err=>{
          if(err){console.log(err)}
        })
     }
});

in first time when i add information, it works. But when i have submit for adding info another time i get an error in adding document in student_course_completion collection. the error is-

MongoServerError: E11000 duplicate key error collection: ciu-app.st_course_comlepetion_info index: _id_ dup key: { _id: ObjectId('620de7cb66842616fcdd6c9a') }
        at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\operations\insert.js:51:33
        at F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
        at handleOperationResult (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\sdam\server.js:363:9)
        at MessageStream.messageHandler (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\connection.js:479:9)

        at MessageStream.emit (events.js:400:28)
        at processIncomingData (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
        at MessageStream._write (F:\senior project\ciu-app-practise\ciu-app-db\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
        at writeOrBuffer (internal/streams/writable.js:358:12)
        at MessageStream.Writable.write (internal/streams/writable.js:303:10)
        at TLSSocket.ondata (internal/streams/readable.js:731:22) {
      index: 0,
      code: 11000,
      keyPattern: { _id: 1 },
      keyValue: { _id: new ObjectId("620de7cb66842616fcdd6c9a") } }

but when i re-render my server file(node js file) and then add information, it does not shows the error.so after adding one iformation, always i have to re-render the server, otherwise it shows me the error of duplicate key.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source