node.js 和 mongodb 查找并删除

node.js and mongodb find and delete

大家好,我是一般编程新手,我正在尝试在 node.js 中编写查询以显示我的数据库中的最低分数,然后稍后将其删除。我的数据看起来像这样

{
"_id" : 19,
"name" : "Gisela Levin",
"scores" : [
    {
        "type" : "exam",
        "score" : 44.51211101958831
    },
    {
        "type" : "quiz",
        "score" : 0.6578497966368002
    },
    {
        "type" : "homework",
        "score" : 93.36341655949683
    },
    {
        "type" : "homework",
        "score" : 49.43132782777443
    }
]
}

所以我需要单独查找并删除最低的作业,而不是两者。在我写的代码中,我试图先显示这些最低的,然后我将删除它们。到目前为止,我写的这段代码显示了这样的分数

'Verdell Sowinski scored 69.09840625499065'

'Verdell Sowinski scored 17.90304994248164'

'Vina Matsunaga scored 19.16579262350994'

'Vina Matsunaga scored 8.217818112853726'

'Vinnie Auerbach scored 23.91300715707971'

'Vinnie Auerbach scored 53.31631231243156'

'Whitley Fears scored 92.2308421188758'

'Whitley Fears scored 97.95928979563497'

'Wilburn Spiess scored 10.53058536508186'

'Wilburn Spiess scored 28.10477578379966'

'Zachary Langlais scored 19.21886443577987'

'Zachary Langlais scored 8.548735651522431'

'aimee Zank scored 6.676176060654615'

'aimee Zank scored 18.52035674134503'

这是我目前所拥有的:

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

    var cursor = db.collection('students').find().sort({name : 1});
    var list = [];
    var count = 0;
    var currentName = '';

    cursor.each(function(err, doc){
        if(err) throw err;

    if(doc == null){
        return
    }
    
    var lowestScore = 1000;
    var lowestScore_position = '';

    for(i=0; i<doc.scores.length; i++){
        if (doc.scores[i].type == 'homework' && doc.scores[i].score<=lowestScore) {
        lowestScore = doc.scores[i].score;
        lowestScore_position = i;
            
        }
    }
    console.dir(doc.name + " scored " + lowestScore);
    });
});

提前致谢

var MongoClient = require('mongodb').MongoClient;

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

   var cursor = db.collection('students').find();

   var lastStudent = '';

   cursor.each(function(err, doc){
      if (err) throw err;

      if (doc == null) {
          setTimeout(function() {
              return db.close()
          }, 2000);
      } else {

          var lowScoreIndex = -1;
          var lowScore = 100;

          Array.prototype.forEach.call(doc.scores, function(score) {
              if (score.type === 'homework') {
                  if (score.score < lowScore) {
                      lowScore = score.score;
                      lowScoreIndex = Array.prototype.indexOf.call(score, lowScore);
                  }
              }
          });

          doc.scores.splice(lowScoreIndex, 1);

          db.collection('students').update({'_id':doc['_id']}, doc, function(err, updated) {
              if (err) throw err;
          })
      }

   });
});