Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: db.admin is not a function

I'm learning Mongo DB, I'm trying to list all the dbs,I got this error after giving URL to the

var dbAdmin=db.admin()

var mongoClient = require('mongodb').MongoClient;
mongoClient.connect("mongodb://localhost/",
    {useUnifiedTopology: true,useNewUrlParser:true, poolSize: 5, reconnectInterval: 500 },
    function(err,db){
        console.log("DATABASE IS BEING LOGGED...." ,db);
        var dbAdmin=db.admin();
    dbAdmin.listDatabases(function (err,databases) {
        console.log("before adding databases");
        console.log(databases);
    })
    });
var dbAdmin=db.admin(); ^

TypeError: db.admin is not a function

I have consoled the DB object it returns JSON, it does not have the function I have followed this code from the book Node.js, MongoDB and Angular Web Development, by brad dayley 2018 edition

like image 914
parveen mittal Avatar asked Oct 15 '22 10:10

parveen mittal


1 Answers

After looking here https://mongodb.github.io/node-mongodb-native/3.3/api/ I got it working by modifying your code (I am guessing that in your case to apply .admin() method you need Db object but your db is not Db object but MongoClient object). Just changing var dbAdmin=db.admin() to var dbAdmin=db.db('test').admin() works or:

var mongoClient = require('mongodb').MongoClient;
var dbName = 'test';
mongoClient.connect("mongodb://localhost/",
{useUnifiedTopology: true,useNewUrlParser:true, poolSize: 5, reconnectInterval: 500 },
function(err,client){
    //console.log("DATABASE IS BEING LOGGED...." ,client);
    var dbAdmin=client.db(dbName).admin();
dbAdmin.listDatabases(function (err,databases) {
    console.log("before adding databases");
    console.log(databases);
    client.close();
})
});

And btw 'test' is just arbitrary.

like image 156
oktogen Avatar answered Oct 20 '22 00:10

oktogen