node.jsmongodbexpressmongoosemongoexport

Cannot run command in Mongoose


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

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

mongoexport -c appointment -o appointments_2021_04_10_9_52.json

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.