【问题标题】:unexpected identifier - javascript,node and mongodb意外标识符 - javascript、node 和 mongodb
【发布时间】:2015-06-06 14:52:17
【问题描述】:

运行下面的代码时,在检查文档状态是否已更改时出现意外的标识符错误。我已经用谷歌搜索死了。试图在 Mongodb、here 和其他杂项资源中找到文档,但没有任何运气。我花了一整天的时间,现在感觉很愚蠢。

衷心感谢所有帮助。

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;

   ;})
});

});

【问题讨论】:

  • IMO 这通常是由于缺少属性之间的逗号或代码中的大括号而发生的。

标签: javascript node.js mongodb


【解决方案1】:

我认为在 google 上很难找到意外的标识符。您可能有额外的右大括号或右括号。

我没有看到这个左括号的右括号:

MongoClient.connect(

【讨论】:

    【解决方案2】:

    if prevState != doc.state{改为if (prevState != doc.state) {——即:添加一对()

    要轻松找到此类问题,您应该使用 Javascript 语法检查器。谷歌这个词,你会得到一些不错的结果。

    另请注意,您的代码中至少还有一个其他语法问题 weather.update(operation,function(err,doc)); 您使用了 function 关键字,但不提供函数体。要使其通过语法检查,您至少应该这样做:weather.update(operation,function(err,doc) {}); 但您可能想在花括号 {} 内添加一些逻辑。

    这是由http://esprima.org/demo/validate.html检测到的

    还有一件事,与原始问题无关: 您在代码中使用throw 来报告错误。由于 node/mongo 主要使用异步 API,抛出异常几乎没有意义。看看以下问题:

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 2021-11-05
      • 2016-01-23
      • 2018-03-29
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多