0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

mongoで初期データ作る際に困ったこと

Posted at

基本的にはこのありがたい記事を参考にさせていただいたのですが、うまくいかないところもありました。

docker-entrypoint-initdb.d/1-mongo-init.jsの部分

ユーザーを作る必要あるかないかで認証エラーを起こすため、分岐が必要だった

上記サイトのコード(お借りします)

var user = {
  user: "mongo",
  pwd: "mongo",
  roles: [
    {
      role: "dbOwner",
      db: "mongo_example"
    }
  ]
};

db.createUser(user);
db.createCollection('staffs');

分岐追加ver

//ユーザーを取ってくる
const user = db.getUsers();
//mongoというユーザーがいなかったら作成する
const isExistUser = user.some((u)=> u.user === "mongo");
if(!isExistUser){
    const newUser = {
      user: "mongo",
      pwd: "mongo",
      roles: [
        {
          role: "dbOwner",
          db: "mongo_example"
        }
      ]
    };
    
    db.createUser(newUser);
}
const targetDB = db.getSiblingDB("mongo_example");
targetDB.createCollection('staffs');

docker-entrypoint-initdb.d/2-mongo-init.shの部分

CRLF→LFにして書き方も工夫しないといけなかった

これはWindowsの問題みたいなのですが、Windowsでshファイルを作成するとCRLFという形式になるため、mongoで使うためにはLFにする必要がありました。
vsCodeだと、右下にCRLFと記載された箇所があるので、そこをクリックしてLFに変更するのと、コードも以下のように改行を書き換えないといけません。
改行コードについてはこの記事が分かりやすかったです。

//このbashですよ宣言も忘れずに追加しましょう
#!/bin/bash

mongoimport \
  -u mongo \
  -p mongo \
  --authenticationDatabase mongo_example \
  --db mongo_example \
  --collection staffs \
  --file /docker-entrypoint-initdb.d/staffs.json \
  --jsonArray

まとめ

大変ありがたい記事にケチを付けるような風になってしまって申し訳ないです。
ですが、Windows環境だと少し違ったので、誰かの参考になればと思います。
最後に、ありがたい記事をもう一度貼って終わりにします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?