LoginSignup
36
36

More than 3 years have passed since last update.

【2019年版】Node.js + MongoDBでデータベース接続をする【Mac環境】

Last updated at Posted at 2019-11-04

そろそろReactのバックエンドをNode.jsで書きたいと思ってきた頃なので、最近熱いNoSQLをNode.jsで使う方法をまとめました!

準備体操

HomebrewとNode.jsは入ってますか?

$ brew -v
Homebrew 2.1.15
Homebrew/homebrew-core (git revision 1ea06; last commit 2019-11-04)
Homebrew/homebrew-cask (git revision 932c87a; last commit 2019-11-04)
$ node -v
v11.6.0

コマンドを打っても何も出てこない時は、以下からインストールしてください。
MacにHomebrewとNode.jsをインストール

みんな大好きmacOSで開発していきますよ。

環境構築

まずは、MongoDBをMacにインストールします。

とりあえずホームディレクトリ~/で以下のコマンド

$ brew tap mongodb/brew

MacにMongoDBをインストール

brew install mongodb-community@4.2

mongoコマンドを打ってこんな感じになればOK

$ mongo
MongoDB shell version v4.2.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
︙

MongoDBをローカル環境で使うために、データベースを起動しておく必要があります。
以下のコマンドでMongoDBを起動します。

$ mongod --config /usr/local/etc/mongod.conf

ここでは特に出力されないので、新しいターミナルを開いてMongoDBが起動しているか確認。

//新しいターミナル画面で

$ mongo
MongoDB shell version v4.2.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
︙
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

ターミナルが入力待ちになっていたら、成功。
control^ + Cでシェルを終了します。

mongod --config /usr/local/etc/mongod.confaliasに登録しておくと捗ります。
aliasについてはこちらの記事がおすすめです。
【初心者向け】エイリアスの設定方法

私は、mongodbでサーバーが起動するaliasを登録しています。

MongoDBを使用する場合は、サーバーを起動したまま作業をしてください。(mongod --config /usr/local/etc/mongod.confを使用したまま)
たぶん、コマンド打たなくて自動で起動してくれるみたいな便利グッズがありそうですが、気力が持たなかったのでまたいつか調べます。

さあ、準備万端です。
Javascriptを書いていきましょう。

JavascriptとMongoDBを接続

まずは作業ディレクトリを作りましょう。

$ mkdir mongo-curd
$ cd mongo-curd

MongoDBをnode.jsで使えるようにするDriverをnpmでインストールします。

$ npm init -y
$ npm install mongodb --save

実際のnode.jsを書いていくファイルを作成します。

$ touch index.js

index.jsファイルが作成できたら以下のコードをindex.jsに記述してください。

index.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

/* 接続先URL */
const url = 'mongodb://localhost:27017';

/* データベース名 */
const dbName = 'myMongo';

/* データベース接続 */
MongoClient.connect(url, (err, client) => {

  /* Errorがあれば処理を中断 */
  assert.equal(null, err);

  /* 接続に成功すればコンソールに表示 */
  console.log('Connected successfully to server');

  /** DBを取得 */
  const db = client.db(dbName);

  /* DBとの接続切断 */
  client.close();
});

ファイルを実行してみましょう。


$ node index.js

(node:72067) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, 
and will be removed in a future version. To use the new Server Discover and Monitoring engine, 
pass option { useUnifiedTopology: true } to the MongoClient constructor.
Connected successfully to server

OOPS!

WTF!!

やたらと長ったらしいエラーが吐き出されました。

MongoClientに{ useUnifiedTopology: true }をオプションとして渡せとのことです。
index.jsを以下のように変更しましょう。

index.js

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

/* 接続先URL */
const url = 'mongodb://localhost:27017';

/* データベース名 */
const dbName = 'myMongo';

/**
 * 追加オプション
 * MongoClient用オプション設定
 */
const connectOption = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}

/**
 * データベース接続
 * データベース接続用の引数追加
 */
MongoClient.connect(url, connectOption, (err, client) => {

  /* Errorがあれば処理を中断 */
  assert.equal(null, err);

  /* 接続に成功すればコンソールに表示 */
  console.log('Connected successfully to server');

  /** DBを取得 */
  const db = client.db(dbName);

  /* DBとの接続切断 */
  client.close();
});

MongoClient.connect(url, connectOption, (err, client))の第二引数にconnectOptionを渡していることに注意してください。

さあ、もう一度、実行してみましょう。

$ node index.js
Connected successfully to server

無事、MongoDBとの接続できました。

次回は、これを使ってもう少し本格的に、データベースには欠かせないCURDの実装していきます。

それでは!

Happy Hacking :sunglasses: !

参考

Install MongoDB Community Edition on macOS

MongoDB Quick Start

36
36
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
36
36