ホームページ  >  記事  >  ウェブフロントエンド  >  Nodejs を使用して mongodb データベースに接続する方法に関する詳細なチュートリアル

Nodejs を使用して mongodb データベースに接続する方法に関する詳細なチュートリアル

巴扎黑
巴扎黑オリジナル
2017-08-22 17:04:442139ブラウズ

この記事では、主に Nodejs を使用して mongodb データベースに接続する実装コードを紹介します。必要な方は参考にしてください。

mongodb 公式の例からの、nodejs を使用した接続の簡単な例です

1. パッケージを作成します。 .json

まず、プロジェクトディレクトリconnect-mongodbを作成し、現在のディレクトリとして


mkdir connect-mongodb
cd connect-mongodb
npm init命令创建package.jsonを入力します


npm init

次に、mongodb


npm install mongodb --save
のnodejsバージョンドライバーをインストールします

モンゴデータベースドライバーパッケージは現在のディレクトリのnode_modulesにインストールされます

2. MongoDBサーバーを起動します

MongoDBをインストールし、MongoDBデータベースサービスを起動します。以前の記事、またはMongoDBの公式ドキュメントを参照してください

。 3. MongoDB に接続します

app.js ファイルを作成し、次のコードを追加して、サーバー アドレス 192.168.0.243 および mongodb ポート 27017 上の myNewDatabase という名前のデータベースに接続します


var MongoClient = require('mongodb').MongoClient,
  assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  db.close();
});

app.js を実行するコマンド ライン


node app.js

4. ドキュメントを挿入します

app.js に次のコードを追加し、insertMany メソッドを使用して 3 つのドキュメントをドキュメント コレクションに追加します


insert コマンドは、次のプロパティを含むオブジェクトを返します:

  • result MongoDB によって返されるドキュメントの結果

  • ops _id フィールドが追加されたドキュメント

  • connection 挿入操作の実行に使用される接続

app.js の次のコードを更新して、insertDocuments メソッドを呼び出します


var insertDocuments = function(db, callback){
  // get ths documents collection
  var collection = db.collection('documents');
  // insert some documents
  collection.insertMany([
    {a:1},{a:2},{a:3}
  ],function(err,result){
    assert.equal(err,null);
    assert.equal(3,result.result.n);
    assert.equal(3,result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
};

ノード app.js を使用してコマンドラインで実行します

5. すべてのドキュメントをクエリします

findDocuments 関数を追加します


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  db.close();
 });
});

findDocuments 関数は、すべての「ドキュメント」コレクション内のすべてのドキュメントをクエリします。この関数を MongoClient.connect のコールバック関数に追加します


var findDocuments = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // find some documents
  collection.find({}).toArray(function(err,docs){
    assert.equal(err,null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
};

6. クエリ フィルターを使用してドキュメントをクエリします

Query 'a' のドキュメント:3


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected correctly to server");
 insertDocuments(db, function() {
  findDocuments(db, function() {
   db.close();
  });
 });
});

7. ドキュメントの更新


var findDocuments = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('documents');
 // Find some documents
 collection.find({'a': 3}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  callback(docs);
 });   
}

updateDocument メソッドは、条件 a が 2 を満たす最初のドキュメントを更新し、 b 属性を追加して、それを次のように設定します。 1.

MongoClient.connectメソッドのコールバックにupdateDocumentメソッドを追加


var updateDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // update document where a is 2, set b equal to 1
  collection.updateOne({a:2},{
    $set:{b:1}
  },function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("updated the document with the field a equal to 2");
    callback(result);
  });
};

8. ドキュメントを削除


MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});

app.jsに追加


var removeDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // remove some documents
  collection.deleteOne({a:3},function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("removed the document with the field a equal to 3");
    callback(result);
  });
};

9. インデックスを作成する

インデックスはアプリケーションのパフォーマンスを向上させることができます。コードの下に、「a」属性のインデックスを追加します


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  updateDocument(db, function() {
   removeDocument(db, function() {
    db.close();
   });
  });
 });
});

app.jsを更新してください


var indexCollection = function(db,callback){
  db.collection('documents').createIndex({
    a:1
  },null,function(err,results){
    console.log(results);
    callback();
  });
};

以上がNodejs を使用して mongodb データベースに接続する方法に関する詳細なチュートリアルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。