0

I find that after connecting to MongoDB from Node.js, the db variable I get seems to have limited powers; I can use it to add documents to a collection, but if I try to call db.getSiblingDB(), I'm told "db.getSiblingDB is not a function".

Can anyone explain what's going on here please? I'm using the latest (Nov 2018) MongoDB, Node.js, with driver installed via npm.

The following code is the "Connect to MongoDB" example code lifted straight from mongodb.github.io, with the penultimate line added by me to illustrate the problem. It's runnable as-is.

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

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  // Now try this...
  const test = db.getSiblingDB('test');   // -> "db.getSiblingDB is not a function"

  client.close();
}); 
  • 1
    It's just `client.db('test')` just like the earlier call. The only available methods are listed on [`MongoClient`](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html) in the documentation. There is no such method on the [`Db`](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html) object, because you're meant to use the `MongoClient` instance. – Neil Lunn Nov 24 '18 at 00:54
  • Finally the penny drops. I'd assumed (..quite wrongly) that when the driver gave me a db, it was the familiar db variable from my many learner examples. However the documentation says otherwise, and your comment sums that up neatly - thank you. Note to self: **RTFM**, and believe what it says. – anotherStacker Nov 24 '18 at 10:50

0 Answers0