You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js操作MongoDb报错TypeError: db.close is not a function求助

解决MongoDB Node.js应用中TypeError: db.close is not a function错误

这个错误的原因很明确——你用了MongoDB Node.js驱动的新API,但还在沿用旧版本的连接关闭方式。

在较新的MongoDB驱动(3.x及以上版本)中,db对象已经不再提供close()方法了,关闭数据库连接的操作需要通过**客户端实例(也就是你代码里的client参数)**来执行,而不是调用db.close()。

看一下你的代码,最后一行的db.close()就是问题所在,把它换成client.close()就能解决这个错误。

修改后的完整代码

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) { 
  if(err) throw err;
  const db = client.db('demo'); 
  console.log('Successfully connected'); 

  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'); 
        // 这里改成client.close()
        client.close(); 
      }); 
    }); 
  }); 
});

额外建议

另外,嵌套回调的写法容易让代码变得混乱,推荐你使用ES6的async/await语法来重构代码,让逻辑更清晰:

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

async function runDemo() {
  const demoPerson = { name:'John', lastName:'Smyth' }; 
  const findKey = { name: 'John' }; 
  let client;

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

    const collection = db.collection('people');
    const insertResult = await collection.insertOne(demoPerson);
    console.log('Inserted', insertResult.ops[0]);
    console.log('ID:', demoPerson._id);

    const foundResults = await collection.find(findKey).toArray();
    console.log('Found results:', foundResults);

    const deleteResult = await collection.deleteOne(findKey);
    console.log('Deleted person');
  } catch (err) {
    console.error(err);
    throw err;
  } finally {
    if (client) {
      await client.close();
    }
  }
}

runDemo();

内容的提问来源于stack exchange,提问作者runnerpaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:47:42