我正在浏览mongoose quickstart并且我的应用程序因{1}}错误而死于fluffy.speak()
教程中的我(稍加修改)代码:
TypeError: Object { name: 'fluffy', _id: 509f3377cff8cf6027000002 } has no method 'speak'
答案 0 :(得分:9)
当您致电db.model
时,模型将根据您的架构进行编译。就在那时,schema.methods
被添加到模型的原型中。因此,您需要在之前定义架构上的任何方法。从中创建模型。
// ensure this method is defined before...
kittySchema.methods.speak = function() {
var greeting = this.name ? "Meow name is" + this.name : "I don't have a name";
console.log(greeting);
}
// ... this line.
var Kitten = db.model('Kitten', kittySchema);
// methods added to the schema *afterwards* will not be added to the model's prototype
kittySchema.methods.bark = function() {
console.log("Woof Woof");
};
(new Kitten()).bark(); // Error! Kittens don't bark.