我目前正在使用带有 Express-Jade 的 AngularJS 和带有 Coffeescript 的 Mongoose。目录结构分为模型视图控制器。
这是模型中的 post.coffee
mongoose = require("mongoose")
Schema = mongoose.Schema
postSchema = new Schema(
title:
type: String
default: ""
trim: true
body:
type: String
default: ""
trim: true
)
postSchema.path("title").validate ((title) ->
title.length > 0
), "Post title cannot be blank"
postSchema.path("body").validate ((body) ->
body.length > 0
), "Post body cannot be blank"
Post = mongoose.model("Post", postSchema)
这是控制器中的 post.coffe
mongoose = require("mongoose")
Post = mongoose.model("Post")
# _ = require("underscore")
# GET
exports.posts = (req, res) ->
pList = Post.find
posts = []
pList.forEach (post, i) ->
posts.push
id: i
title: post.title
text: post.text.substr(0, 50) + "..."
res.json posts: posts
这个片段来自 app.coffee
# Bootstrap models
models_path = __dirname + "/models"
model_files = fs.readdirSync(models_path)
model_files.forEach (file) ->
require models_path + "/" + file
但是,控制器中的 post.coffee 向我抛出了一个错误: MissingSchemaError: Schema has not been registered for model "Post"
我知道这个错误可以通过在控制器的 post.coffee 中添加 Post = mongoose.model("Post") 来解决。但是,是否可以全局声明这个“Post”变量?