Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I am doing a node.js and mongo assignment...
- The test is to loop through a mongoDB find the lowest grade scores, and remove them. I was able to write something that would find the lowest grades, remove them from a secondary var with splice()
- but now I want to update the original document with the new array... and this is the part I am having difficulty with.
- the first code is really just the PRETTY() version of some mondodb records that I am querrying... the SCORES array is the important part.
- The second program will create a doc and doc.scores with the corrected data. But I am trying to update the original DOC with the new data. Not sure how to do this.
- ~~~
- > db.students.find({_id:113}).pretty();
- {
- "_id" : 113,
- "name" : "",
- "scores" : [
- {
- "type" : "exam",
- "score" : 77.57315913088024
- },
- {
- "type" : "quiz",
- "score" : 13.28135073340091
- },
- {
- "type" : "homework",
- "score" : 67.27527802263116
- },
- {
- "type" : "homework",
- "score" : 55.74198976046431
- }
- ]
- }
- ~~~
- my program would splice out doc.scores[1] which has the lowest score.
- Now I want to update the original db. My code is below...
- ~~~
- var MongoClient = require('mongodb').MongoClient;
- MongoClient.connect('mongodb://localhost:27017/school',
- function(err, db) {
- if(err) throw(err);
- var cur = db.collection('students').find({}).sort({name:1});
- var updates = 0;
- var curDone=false;
- cur.each(function(err, doc){
- if(err) throw err;
- if (doc != null){
- console.dir(doc._id + "-- record "+ doc.name);
- zz = doc.scores;
- zzlowScore = zz[0].score;
- zzlowScoreIndex = 0;
- for(var i = 0, l = zz.length; i < l; i++ ){
- console.dir("========zz--Index "+i+" --- score: "+ zz[i].score);
- if(zzlowScore > zz[i].score){
- //we have a new low score and index
- zzlowScore = zz[i].score;
- zzlowScoreIndex= i;
- };
- };
- console.dir("=== low score Index "+zzlowScoreIndex + " ==lowscore== "+zzlowScore);
- console.dir("..............remove the bad stuff..."+ doc._id);
- doc.scores.splice(zzlowScoreIndex,1);
- zz = doc.scores;
- for(var i = 0, l = zz.length; i < l; i++ ){
- console.dir("====zz--Index "+i+" --- score: "+ zz[i].score);
- };
- console.dir("============================================================================");
- //doc.update({_id:doc._id},{scores:zz});
- //db.collection('students').update({_id:doc._id},{scores:zz});
- //
- //Now I need to pass the new doc.scores back to the DB so it can update scores subarray.
- //But not sure how to do this.
- //cur.update({_id:doc._id},$set:{scores:zz});
- db.schools.update({_id:doc._id},$set:{scores:zz});
- //!!!!!!!!!!!!!! THIS IS THE PART I CAN NOT FIGURE OUT. HOW TO UPDATE ORIGINAL DOC??????
- //return doc.scores;
- }else{
- db.close();
- };
- console.dir("++++++++++++++++++++++++++++++++++++++++++");
- });
- });
- ~~~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement