1

按照http://mongoosejs.com/docs/index.html上的指南,我显然误解了一些基本的东西。为什么不将 shema 应用于我检索的对象?

编码

mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/local');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
    // yay!
});

var kittySchema = mongoose.Schema({
    name: String
})
kittySchema.methods.speak = function () {
    var greeting = this.name
        ? "Meow name is " + this.name
        : "I don't have a name"
    console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema)
var silence = new Kitten({ name: 'Silence' })
var fluffy = new Kitten({ name: 'fluffy' });
silence.save(function (err, silence) {
    if (err) // TODO handle the error
        console.log(err.message);
    else
        silence.speak();
});
fluffy.save(function (err, fluffy) {
    if (err) // TODO handle the error
        console.log(err.message);
    else
        fluffy.speak();
});
Kitten.find(function (err, kittens) {
    if (err) // TODO handle err
        console.log(kittens)
    else {
        for (var kitten in kittens) {
            kitten.speak();
        }
    }
});

输出

Path\TestEx\node_modules\mongoose\lib\utils.js:413
        throw err;
              ^
TypeError: Object 0 has no method 'speak'
    at Promise.<anonymous> (Path\TestEx\app.js:66:20)
    at Promise.<anonymous> (Path\TestEx\node_modules\mongoose\node_modules\mpromise\lib\promise.js:162:8)
    at Promise.EventEmitter.emit (events.js:95:17)
    at Promise.emit (Path\TestEx\node_modules\mongoose\node_modules\mpromise\lib\promise.js:79:38)
    at Promise.fulfill (Path\TestEx\node_modules\mongoose\node_modules\mpromise\lib\promise.js:92:20)
    at C:\Users\Richard\WebstormProjects\TestEx\node_modules\mongoose\lib\query.js:1716:26
    at model.Document.init (Path\TestEx\node_modules\mongoose\lib\document.js:243:11)
    at completeMany (Path\TestEx\node_modules\mongoose\lib\query.js:1714:12)
    at cb (Path\TestEx\node_modules\mongoose\lib\query.js:1677:11)
    at Path\TestEx\node_modules\mongoose\lib\utils.js:408:16
4

1 回答 1

3

您的JavaScript. 检查loop的文档for ... in。它遍历对象的字段,而不是数组。因此,for ... in您应该使用带有迭代器的普通for循环而不是循环:

for (var i = 0; i < kittens.length; i++) {
  kittens[i].speak();
}
于 2013-05-03T11:46:36.237 回答