【问题标题】:Kitten can't speak小猫不会说话
【发布时间】:2021-05-09 16:13:12
【问题描述】:

我正在运行mongoose quickstart,我的应用程序一直在fluffy.speak() 上死机,并出现错误TypeError: Object { name: 'fluffy', _id: 509f3377cff8cf6027000002 } has no method 'speak'

本教程中我的(稍作修改)代码:

"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);
});

【问题讨论】:

  • 大声笑,标题只是尖叫“离题!” :P
  • 是的,我可以!我现在正在说话!

标签: node.js mongodb mongoose


【解决方案1】:

当您调用 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.

【讨论】:

    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多