我需要翻译的内容:
我错过了什么?Mongoose文档说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;
我的测试应用:
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));
});
});
});
我尝试将
mongoose.plugin(testPlugin)
移动到app.js
文件的不同位置,包括连接后等等...但是没有效果。