I’m running through the mongoose quickstart and my app keeps dying on fluffy.speak() with the error TypeError: Object { name: 'fluffy', _id: 509f3377cff8cf6027000002 } has no method 'speak'
My (slightly modified) code from the tutorial:
"use strict";
var mongoose = require('mongoose')
, db = mongoose.createConnection('localhost', 'test');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
var kittySchema = new mongoose.Schema({
name: String
});
var Kitten = db.model('Kitten', kittySchema);
var silence = new Kitten({name: 'Silence'});
console.log(silence.name);
kittySchema.methods.speak = function() {
var greeting = this.name ? "Meow name is" + this.name : "I don't have a name";
console.log(greeting);
};
var fluffy = new Kitten({name: 'fluffy'});
fluffy.speak();
fluffy.save(function(err) {
console.log('meow');
});
function logResult(err, result) {
console.log(result);
}
Kitten.find(logResult);
Kitten.find({name: /fluff/i }, logResult);
});
When you call
db.model, the model is compiled from your schema. It’s at that point thatschema.methodsare added to the model’s prototype. So you need to define any methods on the schema before you make a model out of it.