2

I am iterating over a collection, and for each document, I am removing an element with the lowest score from the scores array.

MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;

//var query = { 'assignment' : 'hw1' };
//var operator = { '$set' : { 'date_returned' : new Date() } };

var students = db.collection('students');
var updateDoc = function(document){
    "use strict"
    console.log('update called');
    db.collection('students').save(document,function(error,updatedDocument){
                if(error){
                    console.log(error);
                    throw error;
                }
                console.dir('successfully updated document: '+updatedDocument);
            });
}
var cursor = students.find({});
cursor.each(function(error,doc){
    "use strict"
    if(err) throw err;
    if(doc==null){
        return;
    }
    doc.scores.sort(function(a,b){
        return a.score-b.score;
    });
    doc.scores.splice(0,1);
    updateDoc(doc);

 });
});

Some of the documents are updated, but I get an error at some point like this.

{ [MongoError: E11000 duplicate key error index: school.students.$_id_  dup key:
 { : 0 }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: school.students.$_id_  dup key: { : 0
}'.......

I can understand that I am doing something wrong relating to asynchronous operation on the db, but I am not able to figure out the exact cause.

Help will be appreciated. Thanks

EDIT: document sample

{ _id: 198,
name: 'Timothy Harrod',
scores:
 [ 
  { type: 'exam', score: 11.9075674046519 },
  { type: 'quiz', score: 20.51879961777022 },
  { type: 'homework', score: 55.85952928204192 },
  { type: 'homework', score: 64.85650354990375 } 
 ] 
}
Vignesh PT
  • 624
  • 12
  • 28

1 Answers1

0

The approach in this answer (https://stackoverflow.com/a/18119789/1011042) solved my problem. But it would be great if someone could please explain the problem with my original approach.

Community
  • 1
  • 1
Vignesh PT
  • 624
  • 12
  • 28