【问题标题】:TypeError: db.close is not a function类型错误:db.close 不是函数
【发布时间】:2018-11-07 21:24:00
【问题描述】:

我有以下使用 MongoDb 的 Node.js 应用程序:

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

var demoPerson = { name:'John', lastName:'Smyth' };
var findKey = { name: 'John' };

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

  var collection = db.collection('people');
  collection.insert(demoPerson, function(err, docs) {
    console.log('Inserted', docs[0]);
    console.log('ID:', demoPerson._id);

    collection.find(findKey).toArray(function(err, results) {
      console.log('Found results:', results);

      collection.remove(findKey, function(err, results) {
        console.log('Deleted person');

        db.close();
      });
    });
  });
});

当我运行它时,我得到了这个错误:

TypeError: db.close is not a function

我不明白为什么这不起作用。有人可以帮忙吗?

【问题讨论】:

  • client.close()。前段时间在 API 中发生了变化,与client.db() 同时发生了变化
  • 是的,尼尔是对的。您应该使用从 MongoClient.connect 返回的 client,而不是 db
  • 谢谢大家。这是一种享受。

标签: javascript node.js mongodb typeerror


【解决方案1】:

正如@Neil Lunn 评论的那样,应该使用client.close() 而不是db.close()

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2013-04-01
    • 2016-03-06
    • 2018-04-28
    • 2019-02-14
    • 2021-10-02
    • 2021-10-30
    • 2018-11-22
    相关资源
    最近更新 更多