Coffee-Script Nodejs和Mongoose

时间:2012-04-16 08:06:52

标签: node.js mongodb coffeescript express mongoose

嘿所有人都试图使用express和mongoose来玩nodejs MVC。

我有以下代码:

mongoose = require 'mongoose'
Schema = mongoose.Schema
mongoose.connect 'mongodb://localhost/quotes'

Quote = new Schema()

Quote.add {
  quote : { type: String, required: true}
  , rank  : Number
}

quote = new mongoose.model 'Quote', Quote


module.exports = 

  index: (req,res, next) ->
    quote.find {}, (err,docs) ->
      res.render docs

当我去运行服务器时,我收到以下内容:

Server started on port 3000

module.js:311
    throw err;
          ^
TypeError: Cannot read property 'Quote' of undefined
    at new <anonymous> (/Users ....

我无法理解为什么它一直在抛出未定义的错误。

修改

这是编译好的JS

var Quote, Schema, mongoose, quote;

mongoose = require('mongoose');

Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/quotes');

Quote = new Schema();

Quote.add({
  quote: {
    type: String,
    required: true
  },
  rank: Number
});

quote = new mongoose.model('Quote', Quote);

module.exports = {
  index: function(req, res, next) {
    return quote.find({}, function(err, docs) {
      return res.render(docs);
    });
  }
};

1 个答案:

答案 0 :(得分:2)

我相信mongoose.model不是构造函数。自从我使用了mongoose以来已经有一段时间了,但我也不记得Schema.add,这些字段应该传递给构造函数调用。所以它看起来像这样:

Quote = new Schema
    quote : { type: String, required: true }
    rank  : Number

quote = mongoose.model 'Quote', Quote

编辑Schema.add很好,它实际上是从构造函数中调用的。它只是在文档中简要提到过。