2

コレクションを反復処理しており、ドキュメントごとに、配列scoreから最小の要素を削除しています。scores

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);

 });
});

一部のドキュメントは更新されていますが、このような時点でエラーが発生します。

{ [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
}'.......

データベースでの非同期操作に関連して何か間違ったことをしていることは理解できますが、正確な原因を突き止めることはできません。

助けていただければ幸いです。ありがとう

編集: ドキュメントのサンプル

{ _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 } 
 ] 
}
4

1 に答える 1