Created
January 30, 2014 12:33
-
-
Save AstakhovArtem/8707515 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MongoClient = require('mongodb').MongoClient; | |
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) { | |
if(err) throw err; | |
function iterate(list, func) { | |
'use strict'; | |
var i, res; | |
if ('length' in list && typeof list !== 'function') { | |
res = []; | |
for (i = 0; i < list.length; i += 1) { | |
res.push(func.call(err, list, list[i], i)); | |
} | |
} else { | |
res = {}; | |
for (i in list) { | |
if (list.hasOwnProperty(i)) { | |
res[i] = func.call(err, list, list[i], i); | |
} | |
} | |
} | |
return res; | |
} | |
db.collection('students').find().sort([['name', 1], ['scores.score', 1]]).toArray(function(err, docs) { | |
if(err) throw err; | |
var lowScores = []; | |
function minScore(scores) { | |
var minScore; | |
iterate(scores, function(scores, elem, i) { | |
if(elem.type == "homework") { | |
if(!minScore){ | |
minScore = elem.score; | |
} else if(minScore > elem.score) { | |
minScore = elem.score; | |
} | |
} | |
}); | |
return minScore; | |
} | |
iterate(docs, function(docs, doc, i ) { | |
var obj; | |
obj = { | |
score: minScore(doc.scores), | |
id: doc._id | |
} | |
lowScores.push(obj); | |
}); | |
iterate(lowScores, function(arr, item, i) { | |
var score = item.score; | |
var id = item.id; | |
console.log(score); | |
db.collection('students').update({_id:id}, {$pullAll: {scores: [{type: 'homework', score: score}]}}, function(err, updated) { | |
if(err) throw err; | |
console.log('successful update' + updated); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment