ExpressからmongoDBを使う
はじめに
NoSQLのDBを触ったこと無いので、勉強をしてみようと言う回。
ついでにExpressから動かせるようにしてみる。
前提条件
インストール
homebrewでインストール。
brew update brew install mongodb
brew install mongodb
で下のエラーが出た。
Error: Xcode alone is not sufficient on Sierra.
Install the Command Line Tools:
xcode-select --install
言われた通りにxcode-select --install
を実行。
インストーラー出て来るのでインストール。
動かしてみる
ここを参考にフォルダを作成する。
mkdir -p /data/db
mongod
で起動。エラッタ。
2018-04-13T20:59:18.279+0900 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused 2018-04-13T20:59:18.280+0900 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed : connect@src/mongo/shell/mongo.js:251:13 @(connect):1:6 exception: connect failed
パーミッションも変えてあげないとダメらしい。
多分次のコメントが出ればOK。
waiting for connections on port 27017
使ってみる
mongo
でターミナルから使ってみる。
操作方法(一部)
コマンド | 説明 |
---|---|
show dbs | データベースの一覧を表示 |
use [DB名] | [DB名]にデータベースを切り替える。無ければ作成。 |
db.createCollection([コレクション名]) | コレクションの作成 |
db.[DB名].insert([データ]) | データ追加。 |
db.[DB名].update([変更前データ],[変更後データ]) | データ更新。 |
db.[DB名].insert([データ]) | データ削除。 |
help | ヘルプ表示 |
db.help() | データベースへの操作ヘルプ |
db.[コレクション名].help() | コレクションへの操作ヘルプ |
使ってみた感じは下記の通り。
# DB作成 > use test switched to db test # コレクション作成 > db.createCollection('testコレクション') { "ok" : 1 } # 作成したものの確認 > show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB # データを入れる > db.test.insert({id:1, name:'test1'}) WriteResult({ "nInserted" : 1 }) # 入れたデータを確認 > db.test.find() { "_id" : ObjectId("5ad4a42e31752cb52c3bc118"), "id" : 1, "name" : "test1" } # まとめても入る > db.test.insert([{id:2, name:'test2'},{id:3,name:'test3'}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) # ホントに入ったか確認 > db.test.find() { "_id" : ObjectId("5ad4a42e31752cb52c3bc118"), "id" : 1, "name" : "test1" } { "_id" : ObjectId("5ad4a4a131752cb52c3bc11a"), "id" : 2, "name" : "test2" } { "_id" : ObjectId("5ad4a4a131752cb52c3bc11b"), "id" : 3, "name" : "test3" } # 更新してみる > db.test.update({id:1},{ $set: {name:'test1Update'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.test.find() { "_id" : ObjectId("5ad4a46831752cb52c3bc119"), "id" : 1, "name" : "test1Update" } { "_id" : ObjectId("5ad4a4a131752cb52c3bc11a"), "id" : 2, "name" : "test2" } { "_id" : ObjectId("5ad4a4a131752cb52c3bc11b"), "id" : 3, "name" : "test3" } # データを消してみる > db.test.remove({id:3}) WriteResult({ "nRemoved" : 1 }) > db.test.find() { "_id" : ObjectId("5ad4a46831752cb52c3bc119"), "id" : 1, "name" : "test1Update" } { "_id" : ObjectId("5ad4a4a131752cb52c3bc11a"), "id" : 2, "name" : "test2" }
Expressから使ってみる
npm install mongodb --save
でNodeから扱うためのモジュールをインストール。
今回インストールしたバージョンが3.0.6だったので、これを参考にjsを作っていく。
'usestrict' const MongoClient = require('mongodb').MongoClient; const test = require('assert'); var db; var collection; // 接続先URL const url = 'mongodb://localhost:27017'; // 接続するDB名 const dbName = 'test'; // MongoDBに接続 const mongoClient = new MongoClient(url); mongoClient.connect(function(err, client) { db = client.db(dbName); }); var col = function() { // とりあえずDB名固定で返す return db.collection('test'); } module.exports.collection = col;
これでDB接続の準備はOKのはず。
Expressから呼び出す為に以前作ったindex.js
を下記のように修正。
'use strict'; // import const express = require('express'); // 作ったjsインポート const db = require('./mongodb'); const app = express(); app.use(express.static('./app/')); app.get('/', (req,res) => { console.log('Hello World!'); }); // '/sel'出来た時に一覧を返す app.get('/sel', (req,res) => { db.collection().find().toArray((err,docs) => { res.send(docs); res.end(); }); }); app.listen(3000, () => { console.log('listen on Port 3000'); });
'localhost:3000/sel'にアクセスすると結果が返ってきた。
[{"_id":"5ad4a46831752cb52c3bc119","id":1,"name":"test1Update"},{"_id":"5ad4a4a131752cb52c3bc11a","id":2,"name":"test2"}]
最後に
とりあえず今回はこれで良しとする。
今後、他の機能を実装できればなーと。