Created
April 17, 2013 11:36
-
-
Save sturadnidge/5403580 to your computer and use it in GitHub Desktop.
M101P week 2 solution in node.js
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
'use strict'; | |
/* | |
* Homework assignment 2.2 for M101P, using node.js | |
* | |
* Notes: this only works because the student id | |
* increments by 1, and also because each student | |
* has more than 1 homework score. If either of | |
* those conditions weren't true, this code would | |
* be totally wrong (and dangerous!). | |
* | |
* At least it does things the 'new' way with | |
* MongoClient and streams... | |
* | |
*/ | |
var MongoClient = require('mongodb').MongoClient | |
MongoClient.connect("mongodb://localhost:27017/students", function(err, db) { | |
if (err) { | |
return console.dir(err); | |
} | |
var grades = db.collection('grades') | |
, stream = grades.find({type: 'homework'}).sort({student_id: 1, score: 1}).stream(); | |
var next_id = 0; | |
stream.on("data", function(item){ | |
var curr_id = item.student_id; | |
if (curr_id == next_id) { | |
console.log('removing item with _id ' + item._id.toString()); | |
grades.remove(item, function(err, result) { | |
if (err) { | |
return console.dir(err); | |
} | |
}); | |
next_id++; | |
} | |
}); | |
stream.on("end", function() { | |
db.close; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment