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?

2
  • Are you able to successfully drop collections that aren't empty with this method? Commented Aug 23, 2018 at 12:14
  • @223seneca no the command was not working at all. Commented Aug 23, 2018 at 13:31

1 Answer 1

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?

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

2 Comments

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? If you do that, then any future problems will have a considerable amount of online documentation to help you find solutions.
@223seneca Actually, there is already an established setup that covers all the other cases. So, I would like to stick to it.

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.