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

1 Answers1

-1

Hii if understood well your question, remove that function in server.js file , if you want to test the db just do this in shell

db = db.getSiblingDB("test") //same as use otherdb

for more information please visit this link

Mongo shell Scripting

The Dead Man
  • 6,229
  • 22
  • 88
  • 151
  • 2
    You didn't understand the question. The question is asking about the NodeJS driver, and not the shell. The method is different. – Neil Lunn Nov 24 '18 at 00:51