2016-08-17 2 views
1

내가 무엇이 누락 되었습니까? 몽구스 문서에서는 mongoose.plugin()이 모든 스키마에 대한 플러그인을 등록했다고합니다. 이것은 작동하지 않습니다. 내 스키마를 각 스키마에 등록 할 수 있습니다.모든 스키마에 몽구스 플러그인을 등록하는 방법은 무엇입니까?

내 플러그인 :

module.exports = function (schema, options) { 

    schema.set('toObject',{ 
     transform: function (doc, ret, options) { 
      return { 
       test: 'It worked!' 
      }; 
     } 
    }); 
}; 

내 스키마 작품 위의

var testPlugin = require('test-plugin.js'); 

var personSchema = mongoose.Schema({ 

    _id : { type: String, default: $.uuid.init }, 

    ssn : { type: String, required: true, trim: true }, 

    first : { type: String, required: true, trim: true }, 
    middle : { type: String, required: true, trim: true }, 
    last : { type: String, required: true, trim: true } 
}); 
personSchema.plugin(testPlugin); 

var model = mongoose.model('Person', personSchema); 

module.exports = model; 

코드, 불행히도. 그러나, 다음 코드는하지 않습니다

var personSchema = mongoose.Schema({ 

    _id : { type: String, default: $.uuid.init }, 

    ssn : { type: String, required: true, trim: true }, 

    first : { type: String, required: true, trim: true }, 
    middle : { type: String, required: true, trim: true }, 
    last : { type: String, required: true, trim: true } 
}); 

var model = mongoose.model('Person', personSchema); 

module.exports = model; 

내 테스트 애플 리케이션 : 나는 연결 후 ... mongoose.plugin(testPlugin) 모든 app.js 오버 파일을 이동하려고했습니다

var testPlugin = require('test-plugin.js'); 
mongoose.plugin(testPlugin); 

mongoose.Promise = global.Promise; 
mongoose.connect(config.db); 
mongoose.connection.on('error', function (err) { 
    if (err) { throw err; } 
}); 
mongoose.connection.once('open', function (err) { 
    if (err) { throw err; } 

    seeds.doSeed(function(err){ 
     if (err) { return process.exit(1); } 

     models.Person.find({}, function(err, people){ 
      if (err) { throw err; } 

      var person = people[0]; 
      var oPerson = person.toObject(); 

      console.log(JSON.stringify(oPerson)); 
     }); 
    }); 
}); 

등 ... 그리고 아무것도 효과가 없습니다.

답변

1

app.js 파일에서도 모델을 시험해보십시오. 어딘가에 mongoose.plugin(testPlugin) 이후.

+0

사실 내 문제이기도합니다. 플러그인을 비동기식으로 설정하고이 설정이 완료되기 전에 실수로 모델을로드했습니다. 따라서 플러그인은 절대로 모델에 적용 할 기회가 없었습니다. –