Saturday, 31 August 2013

Update not working-NodeJs and MongoDB using MongoClient

Update not working-NodeJs and MongoDB using MongoClient

I was going through the mongodb and nodejs course on MongoDBUniversity and
one of the task involves finding the documents which has the highest
recorded temperature for any state and then add a field "month_high" to
it.I am able to find the documents for the state with the highest
temperature but am unable to update it. The code is as below.
Can someone tell me what might I be doing wrong?
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course',function(err,db){
var cursor=db.collection("weather").find();
cursor.sort({"State":1,"Temperature":-1});
var oldState,newState;
cursor.each(function(err,doc){
if(err)throw err;
if(doc==null){
return db.close();
}
newState=doc.State;
if(newState!=oldState){
var operator={'$set':{"month_high":true}};
var query={"_id":doc._id};
console.log(doc._id+" has temp "+doc.Temperature+" "+doc.State);
db.collection("weather").update(doc,operator,function(err,updated){
console.log("hi");//---->Never Logs
if(err)throw err;
console.log(JSON.stringify(updated));
})
}
oldState=newState;
});
});

No comments:

Post a Comment