開発者ドキュメント

Node.jsをVPS上のMongoDBデータベースに接続する方法

序章

このチュートリアルでは、Node.jsを使用してVPSのMongoDBデータベースに接続し、いくつかの基本的なデータ操作を行う方法を示します。

使用される次のソフトウェアコンポーネントは次のとおりです。

MongoDB

「MongoDBはオープンソースのドキュメント指向データベースであり、高性能、高可用性、および容易なスケーラビリティを提供します」

MongoDBに慣れていない場合、またはMongoDBをインストールしていない場合は、最初にこのチュートリアルを確認してください。

MongoDBプロセスが実行されていることを確認しましょう。

ps -ef | grep mongo

出力は次のようになります。

mongodb   1307 	1  0 02:27 ?    	00:00:01 /usr/bin/mongod --config /etc/mongodb.conf 

実行されていない場合は、MongoDBbinディレクトリから次のコマンドを発行します。

mongod

MongoDBに付属しているコンソールクライアントがあります。 起動するには、次のコマンドを発行します。

mongo

次のような出力が表示されます(警告は無視してかまいません)。

MongoDB shell version: 2.4.4
connecting to: test
Server has startup warnings:
Mon Oct  7 20:40:35.209 [initandlisten]
Mon Oct  7 20:40:35.209 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
>

次のコマンドを実行して、既存のデータベースを一覧表示します。

show dbs

次のコマンドを実行して、選択したデータベースを表示します。

db

次のコマンドを実行して「テスト」データベースに切り替え、そこに含まれるコレクションを表示します。

use test
show collections 

コンソールクライアントで使用できるコマンドのリストは次のとおりです。「help」と入力すると、コマンドの完全なリストを取得できます。

show dbs                    #show database names
show collections          #show collections in current database
show users                 # show users in current database
show profile                # show most recent system.profile entries with time >= 1ms
show logs                   # show the accessible logger names
show log [name]          # prints out the last segment of log in memory, 'global' is default
use <db_name>          #  set current database
db.foo.find()                # list objects in collection foo
db.foo.find( { a : 1 } )    #list objects in foo where a == 1
it                                #result of the last line evaluated; use to further iterate
exit                            #quit the mongo shell

Node.js

「Node.jsは、ChromeのJavaScriptランタイム上に構築されたプラットフォームであり、高速でスケーラブルなネットワークアプリケーションを簡単に構築できます。 Node.jsは、イベント駆動型の非ブロッキングI / Oモデルを使用しており、軽量で効率的であり、分散デバイス間で実行されるデータ集約型のリアルタイムアプリケーションに最適です。」

これをインストールしていない場合は、最初にこのチュートリアルの手順に従ってください。

Node.jsプロセスが実行されていることを確認しましょう。

node -v

コマンド出力としてNode.jsバージョンが表示されます。

MongoDBNode.jsドライバー


このドライバーは、MongoDBで公式にサポートされているNode.jsドライバーです。 純粋なJavaScriptで記述されており、MongoDBへのネイティブ非同期Node.jsインターフェースを提供します。

ノードパッケージマネージャー「npm」を使用して、ドライバーをインストールします。

npm install mongodb

MongoDBに接続してデータ操作を実行する


次に、Node.jsアプリケーションがMongoDBに接続できるようにするコードを記述します。 データベースからの接続、書き込み、読み取りの3つの操作について説明します。

コードを実行できるようにするには、新しいファイルを作成する必要があります。これを「app.js」と呼びます。

ファイルを取得したら、好みのエディターを使用して次のコードを追加します。

var MongoClient = require('mongodb').MongoClient
	, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
	if (err) {
    	throw err;
	} else {
    	console.log("successfully connected to the database");
	}
	db.close();
});

次のコマンドを入力して、app.jsファイルを実行します。

node app.js

出力に次の文字列が表示されます。データベースに正常に接続されました。

次に、「test_insert」という名前の新しいコレクションに物事を挿入するロジックを追加しましょう。

var MongoClient = require('mongodb').MongoClient
	, format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
	if(err) throw err;

	var collection = db.collection('test_insert');
	collection.insert({a:2}, function(err, docs) {
    	collection.count(function(err, count) {
        	console.log(format("count = %s", count));
            db.close();
    	});
	});
});

データがデータベースに到達したことを確認するコードの別のブロックを追加します。

var MongoClient = require('mongodb').MongoClient
	, format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
	if(err) throw err;

	var collection = db.collection('test_insert');
	collection.insert({a:2}, function(err, docs) {
    	collection.count(function(err, count) {
        	console.log(format("count = %s", count));
    	});
	});

	// Locate all the entries using find
	collection.find().toArray(function(err, results) {
    	console.dir(results);
    	// Let's close the db
    	db.close();
	});
});

おめでとう! これで、Node.jsアプリケーションを使用して、VPSでMongoDBデータベースに接続し、データを挿入し、データを読み取ることができるようになりました。

資力


提出者:http: //www.geberlabs.com/
モバイルバージョンを終了