连续读取mongodb游标
我正在迭代一个集合,并且对于每个文档,我将从scores
数组中删除具有最低score
的元素。
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 }'.......
我可以理解,我正在做有关数据库asynchronous操作的错误,但我无法弄清楚确切的原因。
帮助将不胜感激。 谢谢
编辑:文档示例
{ _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 } ] }
在这个答案 ( https://stackoverflow.com/a/18119789/1011042 )的方法解决了我的问题。 但是,如果有人能够用我原来的方法解释这个问题,那将是非常好的。