nodejsを使用してmongodbデータベースに接続する

6512 ワード

単純なnodejs接続mongodbの例ですmongodbの公式例から
1.packageを作成する.json
まず、プロジェクトディレクトリconnect-mongodbを作成し、現在のディレクトリとして使用します.
mkdir connect-mongodb
cd connect-mongodb

npm initコマンドを入力してpackageを作成します.json npm init
その後、mongodbのnodejsバージョンdriver npm install mongodb --save mongodbドライバパッケージが現在のディレクトリのnode_にインストールされます.modulesで
2.MongoDBサーバの起動
MongoDBをインストールしてMongoDBデータベースサービスを開始するには、以前の記事やMongoDB公式ドキュメントを参照してください.
3.MongoDB接続app.jsファイルを作成し、サーバアドレス192.168.0.243、mongodbポート27017myNewDatabaseという名前のデータベースに接続するコードを追加します.
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メソッドを使用してdocumentsのセットに3つのドキュメントを追加します.
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);
    });
};
insertコマンドは、次の属性を含むオブジェクトを返します.
  • result MongoDBが返す文書結果
  • opsが追加されました_idフィールドのドキュメント
  • connection挿入操作に用いるconnection
  • app.jsで次のコード呼び出しinsertDocumentsメソッドを更新
    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();
      });
    });
    

    コマンドラインでnode app.jsを使用して実行
    5.すべての文書を問い合わせるfindDocuments関数の追加
    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);
        });
    };
    
    findDocuments関数は、すべての「documents」セット内のすべてのドキュメントをクエリーし、この関数をMongoClientに追加します.connectのコールバック関数で
    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();
        });
      });
    });
    

    6.フィルタ条件を使用してドキュメントをクエリーする
    クエリー'a':3のドキュメント
    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);
      });      
    }
    

    7.文書の更新
    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);
        });
    };
    
    updateDocumentメソッドは、条件aが2である最初のドキュメントを更新し、b属性を追加し、1に設定する.updateDocumentメソッドをMongoClient.connectメソッドのコールバックに追加
    MongoClient.connect(url,function(err,db){
        assert.equal(null,err);
        console.log("Connection successfully to server");
        insertDocuments(db,function(){
            updateDocument(db,function(){
                db.close();
            });
        });
    });
    

    8.文書の削除
    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);
        });
    };
    
    app.jsに追加
    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();
          });
        });
      });
    });
    

    9.索引の作成
    インデックスは、アプリケーションのパフォーマンスを改善します.次は「a」プロパティにインデックスを追加します.
    var indexCollection = function(db,callback){
        db.collection('documents').createIndex({
            a:1
        },null,function(err,results){
            console.log(results);
            callback();
        });
    }; 
    

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

    コードはすでにコードクラウドに管理されています