Reputation: 707
I create NodeJS V8 app and use mongoDB local server.
I had mongoDB version ^2.2.34 and connect to DB
let mongodb = require('mongodb');
let mongoClient = mongodb.MongoClient;
let connection = mongoClient.connect('mongodb://localhost:27017/Test');
let getCollection = function (c) {
return connection.then(function (db) {
return db.collection(c);
});
};
It worked. I update my mongoDB version to ^3.0.1 and have error
(node:16320) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: db.collection is not a function
Why in new version it isn't work and how I can change code?
Upvotes: 0
Views: 222
Reputation: 26899
You are expecting connect()
to still return a db
. Read the Mongo upgrade guide (emphasis mine):
What’s new in 3.0
- Support added for Retryable Writes
- Support added for DNS Seedlists
- Support added for Change Streams
- Support added for sessions
MongoClient.connect
now returns a Client instead of a DB.
With that in mind, your code would look something like this:
const {
MongoClient
} = require("mongodb");
const connection = MongoClient.connect("mongodb://localhost:27017");
function getCollection(c) {
return connection
.then(client => client.db("Test"))
.then(db => db.collection(c));
}
Upvotes: 1