【问题标题】:TypeError in Node.js applicationNode.js 应用程序中的 TypeError
【发布时间】:2018-11-10 02:27:30
【问题描述】:

我从 Node.js 教科书中复制了这个示例程序:

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

var website = {
  url: 'http://www.google.com',
  visits: 0
};

var findKey = {
  url: 'www.google.com'
}

MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
  var db = client.db('demo');
  if(err) throw err;

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

  collection.insert(website, function(err, docs) {

    var done = 0;
    function onDone(err) {
      done++;
      if(done < 4) return;

      collection.find(findKey).toArray(function(err, results) {
        console.log('Visits:', results[0].visits);

        //cleanup
        collection.drop(function() {
          client.close();
        });
      });
    }

    var incrementVisits = {
      '$inc': {
        'visits': 1
      }
    };
    collection.update(findKey, incrementVisits, onDone);
    collection.update(findKey, incrementVisits, onDone);
    collection.update(findKey, incrementVisits, onDone);
    collection.update(findKey, incrementVisits, onDone);
  });
});

当我运行它时它会抛出这个错误:

/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:132
      throw err;
      ^

TypeError: Cannot read property 'visits' of undefined
    at /Users/me/Documents/Beginning NodeJS/update/2update.js:26:43
    at result (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:414:17)
    at executeCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:406:9)
    at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:128:55)
    at self.close (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:905:60)
    at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/utils.js:128:55)
    at completeClose (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:1044:14)
    at Cursor.close (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:1057:10)
    at /Users/me/Documents/Beginning NodeJS/node_modules/mongodb/lib/cursor.js:905:21
    at handleCallback (/Users/me/Documents/Beginning NodeJS/node_modules/mongodb-core/lib/cursor.js:199:5)

我看不出这里有什么问题,但是教科书已经有几年的历史了,而且我已经遇到了代码过时并且无法工作的问题,所以我想检查一下这里是否是这种情况。

【问题讨论】:

  • 您是否尝试过打印结果?有数据吗?
  • 这是因为http://www.google.comwww.google.com 不一样,你得不到结果。此外,您还有代码在一切完成之前删除集合并关闭,并且这些更新不会“按顺序”触发。哪本书?这实际上非常可怕。

标签: node.js mongodb typeerror


【解决方案1】:

这是您正在遵循的一个非常可怕的示例,但基本上存在与http:///www.google.com 复合的错误,这是由于文档中的值与www.google.com 不同而创建的,因此您没有得到结果,它是undefined 尝试从空数组中读取属性时。

基本的修正是解决这个问题,并在所有情况下实际使用findOneAndUpdate(),因为这将自动返回一个文档。

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

var website = {
  url: 'http://www.google.com',
  visits: 0
};

var findKey = {
  url: 'http://www.google.com'
}

MongoClient.connect('mongodb://127.0.0.1:27017/demo', { useNewUrlParser: true }, function(err, client) {
  var db = client.db('demo');
  if(err) throw err;

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

  collection.findOneAndUpdate(
    findKey, website, { upsert: true },function(err, doc) {

    var done = 0;

    function onDone(err,doc) {
      done++;

      console.log("Visits: %s", doc.value.visits);
      if (done >= 4) {
        collection.drop(function(err) {
          client.close();
        });
      }

    }

    var incrementVisits = {
      '$inc': {
        'visits': 1
      }
    };

    var options = { returnOriginal: false };

    collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
    collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
    collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
    collection.findOneAndUpdate(findKey, incrementVisits, options, onDone);
  });
});

请注意,最后的“四个”调用不会立即解决。这些只是将异步函数排队,并不能保证它们的执行顺序。

但是脚本会返回:

Visits: 1
Visits: 2
Visits: 3
Visits: 4

一个更好和“现代”的例子应该是:

const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017/";
const options = { useNewUrlParser: true };

const website = {
  url: 'http://www.google.com',
  visits: 0
};

const findKey = { url: 'http://www.google.com' };

(async function() {

  try {

    const client = await MongoClient.connect(uri,options);

    const db = client.db('demo');
    const collection = db.collection('websites');

    await collection.insertOne(website);

    var times = 4;

    while (times--) {
      let doc = await collection.findOneAndUpdate(
        findKey,
        { $inc: { visits: 1 } },
        { returnOriginal: false },
      );
      console.log("Visits: %s", doc.value.visits);
    }

    await collection.drop();
    client.close();

  } catch(e) {
    console.error(e);
  } finally {
    process.exit();
  }

})()

由于我们实际上在await 循环中执行每个调用while,因此我们保证这些实际上是按顺序执行的。我们还 await 一切,所以代码是干净有序的,我们可以在一切完成后挂断数据库连接,而无需等待回调解析或其他方法。

【讨论】:

  • 谢谢。这个答案很有帮助。这本书是 Basarat Ali Syed 的《Beginning Node.js》。我必须承认,在过时的代码和糟糕的示例之间,很难通过。
【解决方案2】:

您的 Mongo 实例似乎返回了某种错误,这使得 results 参数 undefined。因此,请检查前一行中的错误(无论如何您都应该这样做,但可能需要更复杂的错误处理):

 collection.find(findKey).toArray(function(err, results) {

    // this is added
    if( err ) {
      console.log( err );
      return;
    }

    console.log('Visits:', results[0].visits);

    //cleanup
    collection.drop(function() {
      client.close();
    });
  });

【讨论】:

    【解决方案3】:

    代替

     console.log('Visits:', results[0].visits);
    

    尝试打印出来:

     console.log('Visits:', results[0]);
    

    这样您就可以从 results[0] 中检查是否存在属性“visits”

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 2017-10-05
      相关资源
      最近更新 更多