2014-11-09 2 views
7

많은 공통적 인 스키마 정의를 모듈을 통해 내 코드 기반의 다른 모든 모듈에 공유하려고합니다.Node.js에서 외부 모듈의 스키마가 작동하지 않습니다.

var mongoose = require('mongoose'), 
    util = require("util"), 
    Schema = mongoose.Schema; 

var BaseProfileSchema = function() { 
    Schema.apply(this, arguments); 

    this.add({ 
     _user: {type: Schema.Types.ObjectId, ref: 'User', required: true}, 
     name: {type: String, required: true}, 
     bio: {type: String, required: true}, 
     pictureLink: String 
    }); 

}; 
util.inherits(BaseProfileSchema, Schema); 

module.exports = BaseProfileSchema; 

그리고

var mongoose = require('mongoose'), 
    BaseProfileSchema = require('./base_profile_schema.js'), 
    Schema = mongoose.Schema; 

var entSchemaAdditions = { 
    mentors: {type: Schema.Types.ObjectId, ref: 'Mentor'} 
}; 


var entrepreneurSchema = new BaseProfileSchema(entSchemaAdditions); 

module.exports = entrepreneurSchema; 

멘토

도 다른 파일에 정의되어

나는이 두 가지 스키마를 포함하는 myproj_schemas 모듈을 가지고있다.

이 두 가지에 대한 단위 테스트는 스키마 모듈에서 작동합니다.

나는이 모듈을 설치하고 난 다음 오류 얻을

Entrepreneur = db.model('Entrepreneur', entrepreneurSchema), 

사용하여 만들려고 NPM :

형식 오류 : 정의되지 않은 유형 paths.mentors 에서 당신이 스키마를 중첩하려고 했습니까? 심판이나 배열 만 사용하여 중첩 할 수 있습니다.

내 로컬 모듈에서 동일한 코드를 사용하면 문제가 없습니다. require (예 : require ('../ node_modules/myproj_schemas/models/ent_schema')에서 스키마 파일을 직접 참조하는 경우 오류가 발생합니다.)

나는 이것이 이렇게 부서지지 않았 음을 확신합니다. 이전,하지만 난 모든 변경 사항을 백업 한 그것은 여전히 ​​작동하지 않습니다 내가 완전한 빈 그리기있어

을하고, 어떤 제안은 기꺼이받을 것

편집 :.. 나는 '

새로운 스키마 모듈을 만들었습니다. 하나의 스키마가 있습니다 :

var mongoose = require('mongoose'); 

var userSchema = new mongoose.Schema({ 
    email: String 
}); 

module.exports = userSchema; 

모듈에 패키지되어 다른 모듈에 설치되면 실패합니다.

OS에서 실행되는 X 당신이 개인적으로 내가 가진 모든 모델을 등록하는 init 메소드와 별도의 "일반적인"프로젝트를 만들어이 https://github.com/Keeguon/mongoose-behaviors/blob/master/lib/timestampable.js

답변

6

같은 일반적인 스키마에 대한 몽구스 플러그인을 생성하지 않는 이유는

+0

감사합니다. 이 문제를 겪고 있기 때문에 모듈 사이에서 스키마를 공유 할 필요가없는 이러한 유형의 솔루션으로 이동했습니다.나는 왜 문제가 발생했는지에 대해 명확한 생각을 가지고 있다고 느끼지 않지만, 환경이라고 생각하기 시작했으며, 아마도 일부 캐시 지우기가 도움이되었을 것입니다. – JonRed

+0

저는이 대답을 받아 들일 것입니다. 실제로 제 질문에 직접 대답하기 때문에가 아니라, 정상에 올려서 커뮤니티에 가장 도움이 될 것이라고 생각하기 때문입니다. 다시 한 번, 당신의 노력에 감사드립니다. – JonRed

+0

나는 이것을 제대로 작동시키지 못했고,'proxyquire'를 사용하여 내 스키마 정의 모듈에 사용 된 Mongoose 인스턴스를 덮어 써야했습니다. 작동하지만 매우 더러운 것 같습니다. – Mikke

1

mongodb를 호출하고 모델에 액세스해야하는 모든 app의 app.js 파일에서 init 메소드를 호출하십시오.

  1. 공유 프로젝트
    만들기 - 표준 프로세스를 다음 새 노드 프로젝트를 만듭니다. - 공유 프로젝트 내에서 새로운 models 폴더 만들기에

    "main": "index.js" 
    
  2. 이 모델 추가 : -

  3. package.json 공유 프로젝트에서 다음과 같은 항목을 포함하여 package.json 파일을 설정 모든 몽구스 스키마와 플러그인을 포함합니다.modelSchema 파일을 models 폴더에 추가하고 이름을 user.js으로 지정합니다.

    var mongoose = require('mongoose'); 
    
    var userSchema = new mongoose.Schema({ 
        email: String 
    }); 
    
    module.exports = mongoose.model('User', userSchema); 
    
  4. 하는 index.js는 - 그런 다음 프로젝트의 루트 index.js 파일에 모델과 init 방법을 노출하여 앱에서 사용할 수있는 공유 객체를 생성합니다. 내가하고 있어요 방법이이 코드를하는 방법에는 여러 가지가,하지만 여기 :

    function Common() { 
        //empty array to hold mongoose Schemas 
        this.models = {}; 
    } 
    
    Common.prototype.init = function(mongoose) { 
        mongoose.connect('your mongodb connection string goes here'); 
        require('./models/user'); 
        //add more model references here 
    
        //This is just to make referencing the models easier within your apps, so you don't have to use strings. The model name you use here must match the name you used in the schema file 
        this.models = { 
         user: mongoose.model('User') 
        } 
    } 
    
    var common = new Common(); 
    
    module.exports = common; 
    
  5. 참조하여 common 프로젝트 - 당신은 공유 프로젝트를 참조하는 package.json 파일의 공유 프로젝트에 대한 참조를 추가 할 그러나 앱 내에서 common의 이름을 지정하십시오. 개인적으로 GitHub을 사용하여 프로젝트를 저장하고 저장소 경로를 참조했습니다. 저장소가 비공개 였기 때문에 GitHub 지원 사이트에서 다루는 경로의 키를 사용해야했습니다. 앱이의 모델 초기화
  6. - 앱 시작 스크립트에서 당신의 common 프로젝트에 대한 참조를 추가하고 MongoDB를 서버에 연결하는 init 메소드를 호출하고 등록 (의는이 예를 들어 app.js있어 가정하자) 모델. 이제 몽구스가 설립 연결 풀을 가지고 있으며, 모델이 등록되어있는, 당신은 모델을 사용할 수있는 응용 프로그램 내에서 클래스의 인 -

    //at the top, near your other module dependencies var mongoose = require('mongoose') , common = require('common'); common.init(mongoose); 
  7. 를 사용하여 응용 프로그램 어디서나 모델

    . 예를 들어, (단지 예를 들어 쓴, 테스트되지 않은 코드) 당신이 이런 식으로 할 수있는 user에 대한 정보를 표시하는 페이지가 있다고 가정 :

    var common = require('common'); 
    
    app.get('/user-profile/:id', function(req, res) { 
        common.models.user.findById(req.params.id, function(err, user) { 
         if (err) 
          console.log(err.message); //do something else to handle the error 
         else 
          res.render('user-profile', {model: {user: user}}); 
        }); 
    }); 
    

죄송합니다, I didn를 편집 다른 스키마에서 한 스키마를 상속받은 행은 보이지 않습니다. 다른 답변 중 하나로서, 몽구스는 이미 plugin의 개념을 제공합니다. 위의 예에서, 당신은이 작업을 수행 할 것입니다 :

당신의 공통 모듈에서 '/models/base-profile-plugin.js'

하여 일반적인 모듈에서
module.exports = exports = function baseProfilePlugin(schema, options){ 

    //These paths will be added to any schema that uses this plugin 
    schema.add({ 
     _user: {type: Schema.Types.ObjectId, ref: 'User', required: true}, 
     name: {type: String, required: true}, 
     bio: {type: String, required: true}, 
     pictureLink: String 
    }); 

    //you can also add static or instance methods or shared getter/setter handling logic here. See the plugin documentation on the mongoose website. 
} 

아래 '/ 모델/기업에서

var mongoose = require('mongoose') 
    , basePlugin = require('./base-profile-plugin.js'); 

var entrepreneurSchema = new mongoose.Schema({ 
    mentors: {type: Schema.Types.ObjectId, ref: 'Mentor'} 
}); 

entrepreneurSchema.plugin(basePlugin); 

module.exports = mongoose.model('Entrepreneur', entrepreneurSchema); 
1

당신이 기본적으로 찾고있는 것은 스키마 상속을위한이, 몽구스가 실질적으로 문제를 해결 확장라는 이름의 프로젝트, 당신이 그것을 구현하거나 코드를 살펴할지 여부를 결정하는 수 있습니다 거기 된 .js 및 당신 만의 것을 만드세요.

그냥이 어떻게 작동하는지입니다 NPM

$ npm install mongoose-schema-extend 

에게 usng 설치한다 : 같은 완전한 답변을

var mongoose = require('mongoose'), 
    extend = require('mongoose-schema-extend'); 
var Schema = mongoose.Schema; 

var PersonSchema = new Schema({ 
    name : String 
}, { collection : 'users' }); 

var EmployeeSchema = PersonSchema.extend({ 
    department : String 
}); 

var Person = mongoose.model('Person', PersonSchema), 
    Employee = mongoose.model('Employee', EmployeeSchema); 

var Brian = new Employee({ 
    name : 'Brian Kirchoff', 
    department : 'Engineering' 
}); 

관련

+0

이것은 유용한 답변이지만 문제를 해결하지 못합니다. 편집에서 확장되지 않은 스키마에 문제가 있음을 알 수 있습니다. 나는이 문제가 환경 문제라고 점점 더 확신하지만, 아직 다른 기계에서 그것을 증명할 기회를 얻지 못했습니다. – JonRed

관련 문제