Jasjeet Kaur
Jasjeet Kaur

Reputation: 155

Mongodb Shell command execution to drop collection via nodejs

I have a test setup in which mongoimport and mongoexportcommands are used to populate an exiting mongoDB database, say testDB from folder testDump. The problem occurs for the files which are empty in the folder from which testDB is initially populated and then restored.

Eg. a collection file called abcInstance.json is empty in the testDump.

$ cat abcInstance.json
[]

Now when I run some test, this collection gets populated in testDB but at the end when I restore all collections from the testDump folder using mongoimport command it fails for empty files.

So, I am trying to drop those collections using mongo and spawn command.

if (statSync(collectionFile).size === 4) {
const options = [
  'testDB',
  '--eval',
  '"db.abcInstance.drop()"'
];
const dropDB = spawn('mongo', options, { stdio: 'inherit' });
if (dropDB.status !== 0) {
  throw new Error('failed to drop collection ');
}}

But this is also failing and I cannot figure out the error. I have tested that the same command runs successfully on command line:

$ mongo testDB --eval "db.abcInstance.drop()"
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017/alyneKickStartDB
MongoDB server version: 3.6.4
true

Any idea where I am going wrong?

Upvotes: 2

Views: 673

Answers (1)

Jasjeet Kaur
Jasjeet Kaur

Reputation: 155

So, I was able to solve the problem of executing the mongo command by a slightly different approach as stated here.

Basically, the problem I figured out was that my parent process was exiting without waiting for the child process to finish execution as both spawn and exec are asynchronous functions. So I modified my code as follows:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async func test () {
    const res = await exec('mongo testDB --eval "db.abcInstance.drop()" --quiet')
    return { res }
}

Now, when I call this test() function, my collection is successfully dropped.

Does anybody know of any problem with this approach or a better way?

Upvotes: 3

Related Questions