Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Mongo db.runCommand is not a function

I am following this SO question to run a command on Mongo using Node, the command I want to run is:

db.runCommand( { serverStatus: 1, repl: 0, metrics: 0, locks: 0, wiredTiger: 
0, logicalSessionRecordCache: 0, transactions: 0, logicalSessionRecordCache: 
0, tcmalloc: 0, storageEngine: 0, opLatencies: 0, opcountersRepl: 0, 
network: 0, extra_info: 0, asserts: 0, globalLock: 0 } )

But when I try something like:

db.runCommand( { serverStatus: 1 }, function(err, data) {
    if (!err)  console.log(data);
});

or

db.command( { serverStatus: 1 }, function(err, data) {
    if (!err)  console.log(data);
});

or even the one in the question

db.command({ distinct: "Messages", key: "session" }, function (err, data) 
{
    if (!err)  console.log(data);
});

I get a is not a function error:

TypeError: db.runCommand is not a function TypeError: db.command is not a function

Here's my code:

import { MongoClient, Db, ObjectId } from 'mongodb';
...
async pingServer() {
    let connectionStr = 'mongodb://localhost:27017';
    MongoClient.connect(connectionStr, function (err, db) {
        if(!err) {
            db.command({ distinct: "Messages", key: "session" }, function (err, data) {
                if (!err)  console.log(data);
            });
        } else {
            console.log("error",err);
        }
    })
}

I am using mongodb 3.0.6

I also tried doing var MongoClient = require("mongodb").MongoClient; instead of the import (I am working with TypeScript) and got the same result.

What am I doing wrong?

like image 405
Naguib Ihab Avatar asked Nov 18 '22 15:11

Naguib Ihab


1 Answers

You probably have to specify a name for the database, since conncetion.db is a function itself. So if your database is called data you could write:

import { MongoClient, Db, ObjectId } from 'mongodb';
...
async pingServer() {
let connectionStr = 'mongodb://localhost:27017';
MongoClient.connect(connectionStr, function (err, db) {
    if(!err) {
        db("data").command({ distinct: "Messages", key: "session" }, function (err, data) {
            if (!err)  console.log(data);
        });
    } else {
        console.log("error",err);
    }
})

}

like image 75
bolleSat Avatar answered Jan 13 '23 06:01

bolleSat