6

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?

1 Answer 1

3

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);
    }
})

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.