2016-08-17 4 views
1

私は何が欠けていますか? Mongooseのドキュメントでは、mongoose.plugin()はすべてのスキーマのプラグインを登録しています。これは動作していません。私はプラグインを各スキーマに登録できます。すべてのスキーマにmongooseプラグインを登録するには?

私のプラグイン:

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

これは実際に私の問題でした。私はプラグインを非同期にセットアップしていましたが、このセットアップが完了する前に誤ってモデルをロードしました。したがって、プラグインはモデルにそれ自体を適用する機会はありませんでした。 –

関連する問題