簡體   English   中英

Mongodb 通過 shell 插入文檔

[英]Mongodb insert document via shell

我想對我的收藏執行 crud 操作。 為了自動執行此操作,我編寫了一個用於在我的集合中插入文檔的腳本。

這個腳本基本上應該從 json 文件中讀取數據並將其插入到我的數據庫集合中。

'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);
    }
})();

如果我閱讀 json 文件,控制台會記錄以下內容:

[ { 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' } ]

所以 json 對我來說看起來不錯,但如果我執行腳本,它會拋出錯誤:

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

你們中有人知道如何克服這個錯誤嗎?

它顯然沒有看到右括號。 因此,首先嘗試丟掉括號並進行測試。 另外,不要忘記強制“utf8”編碼。

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

線...

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

...缺少括號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM