MongoDB NodeJS (newer) (connect gets client containing db)

博客提到 MongoDB 3.0 中可获取包含数据库对象的客户端对象,相关方法也移至客户端。还给出代码示例,如在不同终端分别执行 mongod、node index.js 以及 http http://localhost:8080/api/tours 等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

According to the changelog for 3.0 you now get a client object containing the database object instead:

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});

The close() method has also been moved to the client. The code in the question can therefore be translated to:

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

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 

----------------------------------------------------------------------------------------------------------------------------------------------------------------- 

const {MongoClient} = require("mongodb");
const url = "mongodb://localhost:27017/";

const findDocuments = (client, callback) => {
  var db = client.db('learning_mongo');
  var collection = db.collection('tours');
  collection.find({"tourPackage": "Snowboard Cali"}).toArray((err, docs) => {
    console.log(docs);
    callback();
  }); 
}

MongoClient.connect(url,{ useNewUrlParser: true }, (err, client) => {
  console.log("MongoDB: you now get a client object containing the database object");
  findDocuments(client, () => {
    client.close();
  })
  // db.close();
})

 

 

 

 

terminal 1: mongod

terminal 2: node index.js

terminal 3: http http://localhost:8080/api/tours

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值