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 that schema.methods
are added to the model's prototype. So you need to define any methods on the schema before you make a model out of it.
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With