【发布时间】:2013-11-23 07:15:24
【问题描述】:
我正在遍历一个集合,并且对于每个文档,我从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
}'.......
我可以理解我做错了与数据库上的异步操作有关的事情,但我无法找出确切的原因。
我们将不胜感激。 谢谢
编辑: 文件样本
{ _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 }
]
}
【问题讨论】:
-
您能否展示您收藏中的文档示例?