Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kitten can't speak

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);
});
like image 990
SomeKittens Avatar asked Nov 11 '12 05:11

SomeKittens


1 Answers

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.
like image 135
numbers1311407 Avatar answered Nov 03 '22 01:11

numbers1311407