0

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;

});





    });

2 Answers 2

3

I'm not 100% sure, but given the syntax reported on the docs you might have to specify the options parameter even if not using it:

db.collection("weather").update(doc,operator, options, function(err,updated)

Also, the connection might get closed before the callbacks are called. Does it change anything if you remove the db.close() call?

Sign up to request clarification or add additional context in comments.

5 Comments

well according to the docs options is optional . I still tried it though as you said but it is still the same.Neither is any error thrown
Is optional unless you want to provide a callback (again, according to the syntax in the docs, but I think I saw it used the way you did). Does it change anything if you remove the db.close() call?
the {db.close()} call is in the if loop...so i guess that should not matter
It could because the callbacks are executed asynchronously, while the if statement is synchronous (executed as soon as the cursor is exhausted)
Yes you were right, it worked... I guess I will have to figure out how to close the db now...If you can edit your answer I can mark it as accepted !:-)
0

Collection name is 'data'. In this homework 'weather' is database name.

See https://education.mongodb.com/courses/10gen/M101JS/2013_October/courseware/CRUD/Homework_2.2/

> use weather
switched to db weather
> db.data.findOne()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.