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

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_33471057/article/details/93157989