Rasmus
Rasmus

Reputation: 8476

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;

});





    });

Upvotes: 0

Views: 2926

Answers (2)

maxp
maxp

Reputation: 5544

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()

Upvotes: 0

Dek Dekku
Dek Dekku

Reputation: 1461

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?

Upvotes: 3

Related Questions