[Fixed] Cannot run command in Mongoose

Issue

Problem Statement

I cannot run a MongoDB command in Mongoose’s model.db.db.admin().command() method. It gives me the error: UnhandledPromiseRejectionWarning: MongoError: no such command: '0'


What I have tried

  • I have tried running it in my CLI and MongoDB Compass Shell to see if it is an error with my command, and it seems it is, and it gives me this error:

SyntaxError: Unexpected token, expected ";" (1:15)

mongoexport -c appointment -o appointments_2021_04_10_9_52.json

  • I have googled for many hours trying to find out how to fix these errors and run a proper command in Mongoose.

Please note: I am quite new to Mongoose/NodeJS and MongoDB. Also, I am running MongoDB locally.


My Code (app.js)

app.get('/exportAllAppoinments', (req, res) => {

    mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {

        const dateTime = moment().format('yyyy_mm_dd_hh_mm');
        console.log(dateTime);

        modelAppointment.db.db.admin().command('mongoexport --collection=appointment --out=appointments_' + dateTime + '.json').then(result => {
            console.log(result);
        });
    },
        err => console.log(err)
    );
});

Expected Results

Mongoose should export the entire collection and send the file back to the frontend.


Actual Results

It does nothing and gives me an error as shown in the beginning.

Solution

modelAppointment.db.db.admin().command() is used to submit a database command to MongoDB.

mongoexport is a command line tool, not a database command.

You might try using exec from child_process to run the command.

Leave a Reply

(*) Required, Your email will not be published