假设您的 main 中需要这样的路由初始化:
module.exports = function(app) {
for (var name in names) {
var schema = new Schema({}) // schema that accepts anything
, m = mongoose.model(name, schema)
, controller = new TextController(m)
app.get('/path', controller.create.bind(controller))
// etc, etc
TextController 在外部定义为:
var TextController = function(Model) {
this.Model = Model
}
TextController.prototype.create = function(req, res) {
var aDoc = this.Model({ // this is the problematic bit
title: req.body.title
, content: req.body.content})
aDoc.save(function(err) {...})
}
出于某种原因,即使标题和内容参数是预期的字符串,mongo 也会将其保存为空文档。正如预期的那样, this.Model 是某种猫鼬对象,但它似乎拒绝保存或实例化。有什么想法或建议吗?
注意:我添加了 controller.method.bind(controller) 因为它是(我知道的)访问 this.Model 的唯一方法。
编辑:我还尝试了以下方法:
var TextController = function(myCollection) {
this.myCollection = myCollection
this.list = function(req, res) {
this.myCollection.find({}, function { ... })
}
}
并且还尝试在函数范围内传入名称并初始化模型function(name) { this.myCollection = mongoose.model(name) ... }