web-dev-qa-db-ja.com

NodeJでMongodbのグローバル接続を処理する最良の方法は何ですか

Node-Mongo-Native を使用してグローバル接続変数を設定しようとしていますが、考えられる2つの解決策の間で混乱しています。どっちがいいのか教えてくれませんか? 1.解決策(すべての要求が新しい接続を作成しようとするため、これは良くありません。)

var express = require('express');  
var app = express();  
var MongoClient = require('mongodb').MongoClient;  
var assert = require('assert');

// Connection URL
var url = '[connectionString]]';

// start server on port 3000
app.listen(3000, '0.0.0.0', function() {  
  // print a message when the server starts listening
  console.log("server starting");
});

// Use connect method to connect to the server when the page is requested
app.get('/', function(request, response) {  
  MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    db.listCollections({}).toArray(function(err, collections) {
        assert.equal(null, err);
        collections.forEach(function(collection) {
            console.log(collection);
        });
        db.close();
    })
    response.send('Connected - see console for a list of available collections');
  });
});
  1. 解決策(アプリの初期化時に接続し、接続文字列をグローバル変数に割り当てる)。しかし、接続文字列をグローバル変数に割り当てるのは良い考えではないと思います。

    var mongodb; var url = '[connectionString]'; MongoClient.connect(url、function(err、db){
    assert.equal(null、err); mongodb = db; });

アプリの初期化時に接続を作成し、アプリのライフタイム全体で使用したいと考えています。

助けてもらえますか?ありがとう。

9
NitinD

アプリデータベース接続を管理するConnectionクラスを作成します。

_const MongoClient = require('mongodb').MongoClient

class Connection {
    static connectToMongo() {
        if ( this.db ) return Promise.resolve(this.db)
        return MongoClient.connect(this.url, this.options)
            .then(db => this.db = db)
    }
}

Connection.db = null
Connection.url = 'mongodb://127.0.0.1:27017/test_db'
Connection.options = {
    bufferMaxEntries:   0,
    reconnectTries:     5000,
    useNewUrlParser: true
}

module.exports = { Connection }
_

_Connection.db_プロパティと同様に、どこでもrequire('./Connection.js')Connection.connectToMongo()メソッドを使用できます。

_const router = require('express').Router()
const { Connection } = require('../lib/Connection.js')

router.get('/files', (req, res) => {
   Connection.db.collection('files').find({})
     .then(files => res.json({ files: files })
     .catch(err => res.json({ error: err })
})

module.exports = router
_
21
Matt

これは私がやった方法です。

            // custom class
            const MongoClient = require('mongodb').MongoClient
            const credentials = "mongodb://user:pass@mongo"

            class MDBConnect {
                static connect (db, collection) {
                    return MongoClient.connect(credentials)
                        .then( client => {
                            return client.db(db).collection(collection);
                        })
                        .catch( err => { console.log(err)});
                }
                static findOne(db, collection, query) {
                    return MDBConnect.connect(db,collection)
                        .then(c => {
                            return c.findOne(query)
                                        .then(result => {
                                            return result;
                                        });
                        })
                }
                // create as many as you want
                //static find(db, collection, query)
                //static insert(db, collection, query)
                // etc etc etc
            }
            module.exports = MDBConnect;


            // in the route file
            var express = require('express');
            var router = express.Router();
            var ObjectId = require('mongodb').ObjectId; 
            var MDBConnect =  require('../storage/MDBConnect');

            // Usages
            router.get('/q/:id', function(req, res, next) {
                let sceneId = req.params.id;

                // user case 1
                MDBConnect.connect('gameapp','scene')
                    .then(c => {
                        c.findOne({_id: ObjectId(sceneId)})
                            .then(result => {
                                console.log("result: ",result);
                                res.json(result);
                            })
                    });
                // user case 2, with query
                MDBConnect.findOne('gameapp','scene',{_id: ObjectId(sceneId)})
                    .then(result => {
                        res.json(result);
                    });
            });
1
roll

モジュールバージョン^ 3.1.8

Promiseとして接続を初期化します。

const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://...'
const client = new MongoClient(uri)
const connection = client.connect()

そして、データベースでアクションを実行したいときはいつでも接続を呼び出します。

app.post('/insert', (req, res) => {
    const connect = connection
    connect.then(() => {
        const doc = { id: 3 }
        const db = client.db('database_name')
        const coll = db.collection('collection_name')
        coll.insertOne(doc, (err, result) => {
            if(err) throw err
        })
    })
})  
1
Henry Bothin