복붙노트

[MONGODB] 어떻게 NodeJs 응용 프로그램 및 모듈에서 MongoDB를 적절히 재사용 연결에

MONGODB

어떻게 NodeJs 응용 프로그램 및 모듈에서 MongoDB를 적절히 재사용 연결에

나는 읽고 읽어 봤는데 여전히 전체 NodeJs 응용 프로그램에서 동일한 데이터베이스 (MongoDB를) 연결을 공유 할 수있는 가장 좋은 방법이 무엇인지에 혼란 스러워요. 내가 알고있는 것처럼 연결이 열려있는 경우 응용 프로그램 시작과 모듈 사이에 재사용해야한다. 가장 좋은 방법은 내 현재의 생각은 그 server.js 데이터베이스에 연결 및 모듈에 전달되는 개체 변수를 생성 (모든 시작은 기본 파일)입니다. 일단 접속이 변수는 필요에 따라 모듈의 코드가 사용되며,이 연결은 열 스테이. 예컨대 :

    var MongoClient = require('mongodb').MongoClient;
    var mongo = {}; // this is passed to modules and code

    MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
        if (!err) {
            console.log("We are connected");

            // these tables will be passed to modules as part of mongo object
            mongo.dbUsers = db.collection("users");
            mongo.dbDisciplines = db.collection("disciplines");

            console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

        } else
            console.log(err);
    });

    var users = new(require("./models/user"))(app, mongo);
    console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined

다음 다른 모듈 모델 / 같은 사용자 외모 :

Users = function(app, mongo) {

Users.prototype.addUser = function() {
    console.log("add user");
}

Users.prototype.getAll = function() {

    return "all users " + mongo.dbUsers;

    }
}

module.exports = Users;

지금은 너무 명백한 문제는이 방법으로 더 나은 그것을 만드는 방법 그렇다면이 있습니다이 잘못되었다는 끔찍한 느낌이?

해결법

  1. ==============================

    1.당신은 몽고와 몽고 DB 인스턴스를 반환하는 모두 연결하는 기능을 가진 mongoUtil.js 모듈을 만들 수 있습니다 :

    당신은 몽고와 몽고 DB 인스턴스를 반환하는 모두 연결하는 기능을 가진 mongoUtil.js 모듈을 만들 수 있습니다 :

    const MongoClient = require( 'mongodb' ).MongoClient;
    const url = "mongodb://localhost:27017";
    
    var _db;
    
    module.exports = {
    
      connectToServer: function( callback ) {
        MongoClient.connect( url,  { useNewUrlParser: true }, function( err, client ) {
          _db  = client.db('test_db');
          return callback( err );
        } );
      },
    
      getDb: function() {
        return _db;
      }
    };
    

    그것을 사용하려면, 당신이 당신의 app.js에서 할 것입니다 :

    var mongoUtil = require( 'mongoUtil' );
    
    mongoUtil.connectToServer( function( err, client ) {
      if (err) console.log(err);
      // start the rest of your app here
    } );
    

    다른의 .js 파일과 같이, 다른 곳 몽고에 대한 액세스를 필요로 할 때 그리고, 당신은이 작업을 수행 할 수 있습니다 :

    var mongoUtil = require( 'mongoUtil' );
    var db = mongoUtil.getDb();
    
    db.collection( 'users' ).find();
    

    이유는이 작품은 모듈 require'd 때 노드에서, 그들은 단지로드 / 당신이 오직 항상 같은 인스턴스를 반환) _db 및 mongoUtil.getDb (의 인스턴스로 끝날 것 때문에 일단 공급받을 것입니다.

    참고, 코드가없는 테스트했다.

  2. ==============================

    2.여기에 내가 이동 - 올렉의 예에 따라, 현대 구문 함께 할 방법입니다. 광산 테스트 기능입니다.

    여기에 내가 이동 - 올렉의 예에 따라, 현대 구문 함께 할 방법입니다. 광산 테스트 기능입니다.

    나는 코드의 일부 의견을했습니다.

     const MongoClient = require('mongodb').MongoClient
     const uri = 'mongodb://user:password@localhost:27017/dbName'
     let _db
    
     const connectDB = async (callback) => {
         try {
             MongoClient.connect(uri, (err, db) => {
                 _db = db
                 return callback(err)
             })
         } catch (e) {
             throw e
         }
     }
    
     const getDB = () => _db
    
     const disconnectDB = () => _db.close()
    
     module.exports = { connectDB, getDB, disconnectDB }
    
     // Load MongoDB utils
     const MongoDB = require('./db/mongodb')
     // Load queries & mutations
     const Users = require('./users')
    
     // Improve debugging
     process.on('unhandledRejection', (reason, p) => {
         console.log('Unhandled Rejection at:', p, 'reason:', reason)
     })
    
     const seedUser = {
         name: 'Bob Alice',
         email: 'test@dev.null',
         bonusSetting: true
     }
    
     // Connect to MongoDB and put server instantiation code inside
     // because we start the connection first
     MongoDB.connectDB(async (err) => {
         if (err) throw err
         // Load db & collections
         const db = MongoDB.getDB()
         const users = db.collection('users')
    
         try {
             // Run some sample operations
             // and pass users collection into models
             const newUser = await Users.createUser(users, seedUser)
             const listUsers = await Users.getUsers(users)
             const findUser = await Users.findUserById(users, newUser._id)
    
             console.log('CREATE USER')
             console.log(newUser)
             console.log('GET ALL USERS')
             console.log(listUsers)
             console.log('FIND USER')
             console.log(findUser)
         } catch (e) {
             throw e
         }
    
         const desired = true
         if (desired) {
             // Use disconnectDB for clean driver disconnect
             MongoDB.disconnectDB()
             process.exit(0)
         }
         // Server code anywhere above here inside connectDB()
     })
    
     const ObjectID = require('mongodb').ObjectID
    
     // Notice how the users collection is passed into the models
     const createUser = async (users, user) => {
         try {
             const results = await users.insertOne(user)
             return results.ops[0]
         } catch (e) {
             throw e
         }
     }
    
     const getUsers = async (users) => {
         try {
             const results = await users.find().toArray()
             return results
         } catch (e) {
             throw e
         }
     }
    
     const findUserById = async (users, id) => {
         try {
             if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
             const results = await users.findOne(ObjectID(id))
             return results
         } catch (e) {
             throw e
         }
     }
    
     // Export garbage as methods on the Users object
     module.exports = { createUser, getUsers, findUserById }
    
  3. ==============================

    3.당신은 Express를 사용하는 경우에, 당신은 당신이 요청 객체에서 DB 연결을 얻을 수 있습니다 특급 - 몽고 - DB 모듈을 사용할 수 있습니다.

    당신은 Express를 사용하는 경우에, 당신은 당신이 요청 객체에서 DB 연결을 얻을 수 있습니다 특급 - 몽고 - DB 모듈을 사용할 수 있습니다.

    설치

    npm install --save express-mongo-db
    

    server.js

    var app = require('express')();
    
    var expressMongoDb = require('express-mongo-db');
    app.use(expressMongoDb('mongodb://localhost/test'));
    

    루트 / users.js

    app.get('/', function (req, res, next) {
        req.db // => Db object
    });
    
  4. ==============================

    4.이이이 곳에서 구성 개체를 받아 쥐게 될 수있는 여러 가지 방법이 있지만,이 코드는 현대 JS 구문을이기는하지만, 배치 얼마나 전반적으로는 비슷. 즉, 귀하의 요구 사항 인 경우 쉽게 프로토 타입과 콜백에 다시 작성할 수 있습니다.

    이이이 곳에서 구성 개체를 받아 쥐게 될 수있는 여러 가지 방법이 있지만,이 코드는 현대 JS 구문을이기는하지만, 배치 얼마나 전반적으로는 비슷. 즉, 귀하의 요구 사항 인 경우 쉽게 프로토 타입과 콜백에 다시 작성할 수 있습니다.

    mongo.js

    const { MongoClient } = require('mongodb');
    const config = require('./config');
    const Users = require('./Users');
    const conf = config.get('mongodb');
    
    class MongoBot {
      constructor() {
        const url = `mongodb://${conf.hosts.join(',')}`;
    
        this.client = new MongoClient(url, conf.opts);
      }
      async init() {
        await this.client.connect();
        console.log('connected');
    
        this.db = this.client.db(conf.db);
        this.Users = new Users(this.db);
      }
    }
    
    module.exports = new MongoBot();
    

    Users.js

    class User {
      constructor(db) {
        this.collection = db.collection('users');
      }
      async addUser(user) {
        const newUser = await this.collection.insertOne(user);
        return newUser;
      }
    }
    module.exports = User;
    

    app.js

    const mongo = require('./mongo');
    
    async function start() {
      // other app startup stuff...
      await mongo.init();
      // other app startup stuff...
    }
    start();
    

    someFile.js

    const { Users } = require('./mongo');
    
    async function someFunction(userInfo) {
      const user = await Users.addUser(userInfo);
      return user;
    }
    
  5. ==============================

    5.약속과 연결을 초기화합니다 :

    약속과 연결을 초기화합니다 :

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

    그리고 당신은 당신이 데이터베이스에 대한 작업을 수행 할 때마다 연결을 전화 :

        // if I want to insert into the database...
        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
            })
        })
    
  6. ==============================

    6.기본적 권리 올렉 - 이동하지만, 요즘 당신은 (아마도) 망가 찾는 사용 "MongoDB를"자체는 오히려 당신을 위해 "더러운 일"을 많이 할 몇 가지 프레임 워크를 사용합니다.

    기본적 권리 올렉 - 이동하지만, 요즘 당신은 (아마도) 망가 찾는 사용 "MongoDB를"자체는 오히려 당신을 위해 "더러운 일"을 많이 할 몇 가지 프레임 워크를 사용합니다.

    예를 들어, 몽구스는 가장 일반적인 중 하나입니다. 이것은 우리가 우리의 초기 server.js 파일에있는 것입니다 :

    const mongoose = require('mongoose');
    const options = {server: {socketOptions: {keepAlive: 1}}};
    mongoose.connect(config.db, options);
    

    이것은을 설정하는 데 필요한 것을 전부입니다. 이제 코드에서이 어디를 사용

    const mongoose = require('mongoose');
    

    그리고 당신은 당신이 mongoose.connect로 설정 해당 인스턴스를 얻을

  7. ==============================

    7.허용 대답을 기반으로하는 테스트 솔루션 :

    허용 대답을 기반으로하는 테스트 솔루션 :

    mongodbutil.js :

    var MongoClient = require( 'mongodb' ).MongoClient;
    var _db;
    module.exports = {
      connectToServer: function( callback ) {
        MongoClient.connect( "<connection string>", function( err, client ) {
          _db = client.db("<collection name>");
          return callback( err );
        } );
      },
      getDb: function() {
        return _db;
      }
    };
    

    app.js :

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    var app = express();
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    var mongodbutil = require( './mongodbutil' );
    mongodbutil.connectToServer( function( err ) {
      //app goes online once this callback occurs
      var indexRouter = require('./routes/index');
      var usersRouter = require('./routes/users');
      var companiesRouter = require('./routes/companies');
      var activitiesRouter = require('./routes/activities');
      var registerRouter = require('./routes/register');  
      app.use('/', indexRouter);
      app.use('/users', usersRouter);
      app.use('/companies', companiesRouter);
      app.use('/activities', activitiesRouter);
      app.use('/register', registerRouter);  
      // catch 404 and forward to error handler
      app.use(function(req, res, next) {
        next(createError(404));
      });
      // error handler
      app.use(function(err, req, res, next) {
        res.locals.message = err.message;
        res.locals.error = req.app.get('env') === 'development' ? err : {};
        res.status(err.status || 500);
        res.render('error');
      });
      //end of calback
    });
    
    module.exports = app;
    

    activities.js - 경로 :

    var express = require('express');
    var router = express.Router();
    var mongodbutil = require( '../mongodbutil' );
    var db = mongodbutil.getDb();
    
    router.get('/', (req, res, next) => {  
        db.collection('activities').find().toArray((err, results) => {
            if (err) return console.log(err)
                res.render('activities', {activities: results, title: "Activities"})
        });
    });
    
    router.post('/', (req, res) => {
      db.collection('activities').save(req.body, (err, result) => {
        if (err) return console.log(err)
        res.redirect('/activities')
      })
    });
    
    module.exports = router;
    
  8. ==============================

    8.우리는 dbconnection.js 같은 dbconnection 파일을 만들 수 있습니다

    우리는 dbconnection.js 같은 dbconnection 파일을 만들 수 있습니다

    const MongoClient = require('mongodb').MongoClient
    const mongo_url = process.env.MONGO_URL;
    
        module.exports = {
            connect: async function(callback) {
                var connection;
                await new Promise((resolve, reject) => {
                    MongoClient.connect(mongo_url, {
                        useNewUrlParser: true
                    }, (err, database) => {
                        if (err)
                            reject();
                        else {
                            connection = database;
                            resolve();
                        }
                    });
                });
                return connection;
            }
    
        };
    

    다음 앱에서 같은에서이 파일을 사용

    var connection = require('../dbconnection');
    

    다음 비동기 함수 내에서 다음과 같이 사용

    db  = await connection.connect();
    

    이 작업을 바란다

  9. ==============================

    9.당신은 다음 코드와 응용 프로그램 편집에 app.js 파일을 몽구스를 사용하기위한 선택하면

    당신은 다음 코드와 응용 프로그램 편집에 app.js 파일을 몽구스를 사용하기위한 선택하면

    app.js

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/Your_Data_Base_Name', {useNewUrlParser:true})
      .then((res) => {
        console.log(' ########### Connected to mongDB ###########');
      })
      .catch((err) => {
        console.log('Error in connecting to mongoDb' + err);
      });`
    

    다음 단계: 응용 프로그램에 대한 모델을 정의를 필요로하고, 예를 들어 직접 CRUD 작업을 수행

    blogSchema.js

     const mongoose = require('mongoose');
     const Schema = mongoose.Schema;
     const blogSchema = new Schema({
         _id : mongoose.Schema.Types.ObjectId,
         title : {
            type : 'String',
            unique : true,
            required : true       
        },
        description : String,
            comments : [{type : mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
     });
     module.exports = mongoose.model('Blog', blogSchema);
    

    용법 createBlog.js

    const Blog = require('../models/blogSchema');
    exports.createBlog = (req, res, next) => {
    const blog = new Blog({
      _id : new mongoose.Types.ObjectId,
      title : req.body.title,
      description : req.body.description,
    });
    blog.save((err, blog) => {
      if(err){
        console.log('Server Error save fun failed');
        res.status(500).json({
          msg : "Error occured on server side",
          err : err
        })
      }else{
        //do something....
      }
    

    U는 .... 항상 MongoDB를 연결할 필요가 없습니다

  10. ==============================

    10.나는 이것에 대한 조금 늦었어요,하지만 난 너무 내 솔루션을 추가합니다. 그것은 여기에 응답에 비해 훨씬 noobier 방식입니다.

    나는 이것에 대한 조금 늦었어요,하지만 난 너무 내 솔루션을 추가합니다. 그것은 여기에 응답에 비해 훨씬 noobier 방식입니다.

    당신이 MongoDB를 버전 4.0과 Node.js를 3.0 (또는 그 이상 버전)를 사용하는 어쨌든 경우는 MongoClient에서는, isConnected () 함수를 사용할 수 있습니다.

    const MongoClient = require('mongodb').MongoClient;
    const uri = "<your connection url>";
    const client = new MongoClient(uri, { useNewUrlParser: true });
    
    if (client.isConnected()) {
      execute();
    } else {
      client.connect().then(function () {
        execute();
      });
    }
    
    function execute() {
        // Do anything here
        // Ex: client.db("mydb").collection("mycol");
    }
    

    이것은 나를 위해 벌금을했다. 희망이 도움이.

  11. ==============================

    11.

    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost:27017/';
    var Pro1;
    
    module.exports = {
        DBConnection:async function()
        {
            Pro1 = new Promise(async function(resolve,reject){
                MongoClient.connect(url, { useNewUrlParser: true },function(err, db) {
                    if (err) throw err;
                    resolve(db);
                });        
            });
        },
        getDB:async function(Blockchain , Context)
        {
            bc = Blockchain;
            contx = Context;
            Pro1.then(function(_db)
            {
                var dbo = _db.db('dbname');
                dbo.collection('collectionname').find().limit(1).skip(0).toArray(function(err,result) {
                    if (err) throw err;
                    console.log(result);
                });
            });
        },
        closeDB:async function()
        {
            Pro1.then(function(_db){
                _db.close();
            });
        }
    };
    
  12. from https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module by cc-by-sa and MIT license