Aksenov Vladimir
Aksenov Vladimir

Reputation: 707

MongoDB 3.0 and mongoDB 2.2

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

Answers (1)

zero298
zero298

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.

Full 3.0 Changes Here


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

Related Questions