0

I want to perform crud operation on my collection. To automate this, I wrote a script for inserting documents on my collection.

This script should basically read the data from a json file and insert it into my db-collection.

'use strict';
const fs = require('fs');
const path = require('path');
const { spawn }= require('child_process');

(function () {
    const username = process.env.DB_USERNAME,
        password = process.env.DB_PASSWORD,
        args = process.argv.slice(3),
        log = console.log,
        mongoServer = "mongodb+srv://***server-name***/";

    let database,
        documents,
        collection;


    if (args.length === 2) {
        database = args[0];
        collection = args[1];

        const raw = fs.readFileSync(path.join(__dirname, 'documents.json'));
        documents = JSON.parse(raw);

        log(documents)
        const writeAction = spawn('mongo', [`\"${mongoServer}${database}\" -u ${username} -p ${password} --eval \"db.${collection}.insert(${documents})\"  `], {shell: true});
        writeAction.stdout.on('data', data => log((`stout: ${data}`));
        writeAction.stderr.on('data', data => log((`StdErr: ${data}`)));
        writeAction.on('close', (code) => log(`Child process exited with code: ${code}.`));
    } else {
        log('A database and a collection has to be specified!\n In Order:\n 1. Database\n 2. Collection');
        process.exit(1);
    }
})();

If I read the json file the console log the following:

[ { id: '3685b542-61d5-45da-9580-162dca725966',
    mission:
     'The American Red Cross prevents and alleviates human suffering in the face of emergencies by mobilizing the power of volunteers and the generosity of donors.',
    street1: '2025 E Street, NW',
    profile_url:
     'https://www.pledgeling.com/organizations/42/american-red-cross' } ]

So the json looks fine to me but if I execute the script it throws me the error:

stout: 2019-11-08T18:08:33.901+0100 E  QUERY    [js] uncaught exception: SyntaxError: missing ] after element list :
@(shell eval):1:23
2019-11-08T18:08:33.901+0100 E  -        [main] exiting with code -4

Does any of you know how to overcome this error?

MarcoLe
  • 2,309
  • 6
  • 36
  • 74

2 Answers2

0

It clearly does not see the closing brackets. So first thing try to lose the brackets and test. Also, do not forget to force 'utf8' encoding.

const raw = fs.readFileSync(path.join(__dirname, 'documents.json'), 'utf8');
documents = JSON.parse(raw);
MEDZ
  • 2,227
  • 2
  • 14
  • 18
  • The brackets are closed und I validated the json json-validator sites and it was fine. – MarcoLe Nov 08 '19 at 17:20
  • Yes I know that. I am saying try to enforce the 'utf8' first .. if it still does not work try to remove both [ ]. – MEDZ Nov 08 '19 at 17:23
0

the line...

writeAction.stdout.on('data', data => log((`stout: ${data}`)); 

... is missing a parenthesis.

barrypicker
  • 9,740
  • 11
  • 65
  • 79