Mongoose:创建新模型时,`TypeError:undefined不是函数`

时间:2015-01-28 21:10:38

标签: node.js mongoose

我正在使用mongoose连接到MongoLab数据库,我将我的数据库模型和东西分开作为我的其余代码的单独模块。我正在尝试创建一个新模型,然后将其保存到数据库中。不幸的是,它不断抛出错误:TypeError: undefined is not a function

这是我的数据库模块

var mongoose = require('mongoose');

module.exports = (function() {
    var database = {};

    database.Schema = mongoose.Schema,
        ObjectID = database.Schema.ObjectID;

    database.Task = new database.Schema({
        task: String, 
    });

    database.Tasks = mongoose.model('Tasks', database.Task);

    return database;
});

以下是生成错误的代码:

var express = require('express');
var database = require('./database');

var router = express.Router();

router.get('/', function(req, res) {
    res.render('../views/index.jade', {title: 'TODO'});
}); 

router.post('/', function(req, res) {
    // res.render('../views/index.jade', {title: 'TODO', tasks: req.body.name});
    var task = new database.Task(req.body.name);
    task.save(function(err) {
        if(!err) {
            console.log('Task: ' + task + 'successfully saved!');
        } else {
            res.render('../views/index.jade', {title: 'Error', tasks: 'Error: ' + err});
        }
    });
});

module.exports = router;

我认为它必须处理database.js的范围,但我不确定。我该如何解决这个问题?

这是完整的Stacktrace

Test
TypeError: Cannot call method 'create' of undefined
    at Object.module.exports [as handle] (E:\backbone_example\include\router.js:
13:28)
    at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
103:13)
    at Route.dispatch (E:\backbone_example\node_modules\express\lib\router\route
.js:107:5)
    at c (E:\backbone_example\node_modules\express\lib\router\index.js:195:24)
    at Function.proto.process_params (E:\backbone_example\node_modules\express\l
ib\router\index.js:251:12)
    at next (E:\backbone_example\node_modules\express\lib\router\index.js:189:19
)
    at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
77:14)
    at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
81:14)
    at Route.dispatch (E:\backbone_example\node_modules\express\lib\router\route
.js:107:5)
    at c (E:\backbone_example\node_modules\express\lib\router\index.js:195:24)

1 个答案:

答案 0 :(得分:1)

.save()是mongoose模型的方法,而不是模式。尝试:

var task = new database.Tasks(req.body.name); task.save(...);

http://mongoosejs.com/docs/api.html#model_Model-save