-1

Running the code below I get an unexpected identifier error when checking if the documents state has changed. I've Googled this to death. tried to find documentation at Mongodb, here, and other misc sources without any luck. Ive spent the whole day on this and feel pretty stupid by now.

All help is sincerely appreciated.

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if (err) throw err;

var weather = db.collection('weather');

var filter = {};
var projection ={'State':1, 'Temperature':1, _id:true};
var options = { 'skip' : 0,
                'limit' : 20000 ,
                'sort' : [['State', 1], ['Temperature', -1]] };
var cursor = weather.find(filter, projection, options);
var month_high = false;
var prevState = '';
var curID = '';
var operation = {'_id':curID,'$set':{'month_high':true}};


// get first document
cursor.first();

// initialize vars
prevState = doc.State;

// cycle through documents
cursor.each(function(err, doc) {
    if(err) throw err;
    if(doc == null) {
        return db.close();
    }
    //Save current document Id
    curID = doc._id;

    // Check if State has changgd 
    if prevState != doc.state{
        //If State has changed update the document 
        weather.update(operation,function(err,doc));
        console.dir(doc); //we expect four documents to ouput.
    }
        // save current doc.state as previous state 
        prevState = doc.State;

   ;})
});

});

2 Answers2

1

I think an unexpected identifier would be difficult to find on google. You may have extra closing braces or closing parentheses.

I don't see a closing parentheses for this opening parentheses:

MongoClient.connect(
Propulsion
  • 503
  • 2
  • 4
  • 14
0

Change the if prevState != doc.state{ to if (prevState != doc.state) { -- that is: add a pair of ( ).

To easily find such problems, you should use a Javascript syntax checker. Google this term and you'll get some good hits.

Also note that you have at least one other syntax problem in your code in weather.update(operation,function(err,doc)); you use the function keyword but does not provide a function body. To make it pass syntax checks you should at least do: weather.update(operation,function(err,doc) {}); but you may want to add some logic inside the curly braces {}.

This was detected by http://esprima.org/demo/validate.html

One more thing, unrelated to the original question: you use throw in your code for reporting errors. As the node/mongo predominantly use async APIs throwing an exception is almost meaningless. Take a look at questions such as:

Community
  • 1
  • 1
Itay Maman
  • 30,277
  • 10
  • 88
  • 118