将自定义实例方法动态添加到猫鼬模式

Sco*_*ott 5 javascript mongoose database-schema node.js

有没有办法在“导出”之后将自定义实例方法添加到猫鼬模式。

例如,如果我有一个架构:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后,我想在将新方法加载到 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();
Run Code Online (Sandbox Code Playgroud)

你有没有尝试过?

我已经尝试将它添加到 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!
Run Code Online (Sandbox Code Playgroud)

jua*_*aco 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)
  })
})
Run Code Online (Sandbox Code Playgroud)

请注意当您进行新的调用时,内部调用schema.add的调用。 Schema