有没有办法在已经“导出”后将custom instance methods添加到mongoose模式中。
例如,如果我有一个架构:
module.exports = function(app, db, config) {
var MySchema = new Schema({ name: String });
MySchema.methods.doIt = function() { console.log("I DID IT!"); }
db.model("MySchema", MySchema);
}
然后我想在已经加载到mongoose模型对象中之后动态地向模式添加新方法。
MySchema = db.model('MySchema');
var obj = new MySchema({name: "robocop"});
var myNewMethod = function() { console.log(this.name); }
// Do Magic here to add the myNewMethod to object.
obj.myNewMethod();
你有没有尝试过?
我已经尝试将它添加到mongoose模型对象中,但这会产生错误,说模式对象没有我刚刚添加的方法。
MySchema = db.model('MySchema');
MySchema.schema.methods.myNewMethod = function() { console.log(this.name); }
db.model('MySchema', MySchema);
console.log(MySchema.schema.methods); // This shows my method was added!
...
var obj = new MySchema({name: "robocop"});
obj.myNewMethod(); //ERROR: YOUR METHOD DOESN'T EXIST!
答案 0 :(得分:0)
您的架构当然受架构对象的影响,而不受模型的任何特定实例的影响。因此,如果要修改架构,则需要访问架构本身。
以下是一个例子:
var mongoose = require('mongoose')
, db = mongoose.connect("mongodb://localhost/sandbox_development")
var schema = new mongoose.Schema({
blurb: String
})
var model = mongoose.model('thing', schema)
var instance = new model({blurb: 'this is an instance!'})
instance.save(function(err) {
if (err) console.log("problem saving instance")
schema.add({other: String}) // teh secretz
var otherInstance = new model({blurb: 'and I am dynamic', other: 'i am new!'})
otherInstance.save(function(err) {
if (err) console.log("problem saving other instance", err)
process.exit(0)
})
})
请注意schema.add
Schema
calls internally when you make a new one的来电。