Programing

단일 node.js 프로젝트의 몽구스 및 다중 데이터베이스

crosscheck 2020. 8. 11. 07:53
반응형

단일 node.js 프로젝트의 몽구스 및 다중 데이터베이스


하위 프로젝트가 포함 된 Node.js 프로젝트를 수행하고 있습니다. 하나의 하위 프로젝트에는 하나의 Mongodb 데이터베이스가 있고 Mongoose는 db를 래핑하고 쿼리하는 데 사용됩니다. 하지만 문제는

  • Mongoose는 모델이 하나의 연결에서 빌드되기 때문에 단일 mongoose 인스턴스에서 여러 데이터베이스를 사용할 수 없습니다.
  • 여러 몽구스 인스턴스를 사용하기 위해 Node.js는 .js 파일에 캐싱 시스템이 있으므로 여러 모듈 인스턴스를 허용하지 않습니다 require(). Node.js에서 모듈 캐싱을 비활성화하는 것을 알고 있지만 몽구스에만 필요하므로 좋은 솔루션이 아니라고 생각합니다.

    내가 사용 해봤 createConnection()openSet()몽구스에 있지만 해결책이 아니었다.

    새 몽구스 인스턴스를 하위 프로젝트에 전달하기 위해 mongoose 인스턴스 ( http://blog.imaginea.com/deep-copy-in-javascript/ ) 를 딥 복사하려고 시도했지만 RangeError: Maximum call stack size exceeded.

몽구스와 함께 여러 데이터베이스를 사용 하거나이 문제에 대한 해결 방법이 있는지 알고 싶습니다. 몽구스는 아주 쉽고 빠르다고 생각하기 때문입니다. 아니면 권장 사항으로 다른 모듈이 있습니까?


한 가지 할 수있는 일은 각 프로젝트에 대한 하위 폴더가있을 수 있다는 것입니다. 따라서 해당 하위 폴더에 mongoose를 설치하고 각 하위 응용 프로그램의 자체 폴더에서 mongoose를 필요로합니다. 프로젝트 루트 또는 글로벌이 아닙니다. 따라서 하나의 하위 프로젝트, 하나의 몽구스 설치 및 하나의 몽구스 인스턴스.

-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/

foo_db_connect.js에서

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;

bar_db_connect.js에서

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;

db_access.js 파일

var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app

이제 mongoose로 여러 데이터베이스에 액세스 할 수 있습니다.


에 따르면 미세 설명서 , createConnection() 수있는 여러 데이터베이스에 연결하는 데 사용된다.

그러나 각 연결 / 데이터베이스에 대해 별도의 모델을 만들어야합니다.

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

나는 당신이 그들 사이에 스키마를 공유 할 수 있다고 확신하지만, 당신은 확인해야한다.


대체 접근 방식으로 Mongoose는 기본 인스턴스에서 새 인스턴스에 대한 생성자를 내 보냅니다. 그래서 이와 같은 것이 가능합니다.

var Mongoose = require('mongoose').Mongoose;

var instance1 = new Mongoose();
instance1.connect('foo');

var instance2 = new Mongoose();
instance2.connect('bar');

이는 별도의 데이터 소스로 작업 할 때 그리고 각 사용자 또는 요청에 대해 별도의 데이터베이스 컨텍스트를 갖고 싶을 때 매우 유용합니다. 이 작업을 수행 할 때 많은 연결을 생성 할 수 있으므로주의해야합니다. 인스턴스가 필요하지 않은 경우 disconnect ()를 호출하고 각 인스턴스에서 생성되는 풀 크기를 제한해야합니다.


Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

mongoose.connect('mongodb://localhost/default');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('connected');
});

which is just how it is described in the docs. And then in your model files, do something like the following:

import mongoose, { Schema } from 'mongoose';

const userInfoSchema = new Schema({
  createdAt: {
    type: Date,
    required: true,
    default: new Date(),
  },
  // ...other fields
});

const myDB = mongoose.connection.useDb('myDB');

const UserInfo = myDB.model('userInfo', userInfoSchema);

export default UserInfo;

Where myDB is your database name.

참고URL : https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project

반응형