gpt4 book ai didi

node.js - 小猫不会说话

转载 作者:IT老高 更新时间:2023-10-28 23:20:46 26 4
gpt4 key购买 nike

我正在浏览 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);
});

最佳答案

当您调用 db.model 时,模型会从您的模式编译。正是在这一点上,schema.methods 被添加到模型的原型(prototype)中。所以你需要在架构上定义任何方法你用它制作模型。

// 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.

关于node.js - 小猫不会说话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com