'In mongoose I have executed the example program given in the website but I'm getting the same error that is: TypeError: fluffy.speak is not a function

const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
    console.log("We are successfully connected");
}
const kittySchema = new mongoose.Schema({
    name: String
});
const Kitten = mongoose.model('Kitten', kittySchema);
const silence = new Kitten({ name: 'Silence' });
console.log(silence.name);
kittySchema.methods.speak = function speak() {
    const greeting = this.name
        ? "Meow name is " + this.name
        : "I don't have a name";
    console.log(greeting);
};

This is not running and showing as not a function const fluffy = new Kitten({ name: 'fluffy' }); fluffy.speak();



Solution 1:[1]

On the Getting Started page for mongoose, it indicates that methods must be declared before calling mongoose.model():

// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function speak() {  
  const greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name";
  console.log(greeting);
};
const Kitten = mongoose.model('Kitten', kittySchema); ```

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Montgomery Watts