2

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?

Jasjeet Kaur
  • 145
  • 1
  • 11

1 Answers1

3

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?

Jasjeet Kaur
  • 145
  • 1
  • 11
  • Personally, I am unfamiliar with using `spawn` with MongoDB. Judging from Google results it doesn't seem super common. Why not just run a separate MongoDB server using [mongod](https://github.com/BrandonZacharie/node-mongod)? If you do that, then any future problems will have a considerable amount of online documentation to help you find solutions. – 223seneca Aug 23 '18 at 18:10
  • @223seneca Actually, there is already an established setup that covers all the other cases. So, I would like to stick to it. – Jasjeet Kaur Aug 23 '18 at 19:42