错误:Route.post()需要回调函数但得到[对象未定义]

时间:2015-09-05 13:05:53

标签: mongodb express mongoose

有回调不知道为什么这不起作用......我有工作用户系统,我基本上只是复制了那个系统。不知道为什么一个有效,另一个没有。我已经省略了不相关的代码,并且在懒惰中包含了用户模型文件中的作业。

错误:Route.post()需要回调函数但得到[对象未定义] 它看起来像这行app.post(' / postjob',jobs.createJob);触发错误。

[index.js]
mongoose.connect(uri);
require('./models/users_model.js');
require('./routes/routes.js')(app);

[routes.js]
module.exports = function(app){

    var jobs = require('../controllers/jobs_controller.js');

    app.all('/postjob', function(req, res){
        if (typeof req.session !== 'undefined' && req.session.user) {
            res.redirect('/');
        }
        res.render('pages/login', {msg:req.session.msg});
    });

    app.post('/postjob', jobs.createJob);
}



[jobs_controller.js]
var mongoose = require('mongoose'),
    Job = mongoose.model('Job');

module.exports = function(app){

    exports.createJob = function(req, res){

        var job = new Job({created: Date.now});
        job.set('title', req.body.title);
        job.set('description', req.body.description);
        job.set('hours', req.body.hours);
        job.save(function(err){
            if (err) {
                alert(err);
            }
            else {
                alert('Job Posted Succesfully');
            }
        });

    }

};

[users_models.js]
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var UserSchema = new Schema ({
    username: { type: String, unique: true },
    email: String,
    color: String,
    hashed_password: String
});

mongoose.model('User', UserSchema);

var JobSchema = new Schema ({
    created: Date,
    postedBy: String,
    title: String,
    description: String,
    hours: String,
    applicants: String,
    closed: Date
});

mongoose.model('Job', JobSchema);

1 个答案:

答案 0 :(得分:3)

我认为问题存在于jobs_controller.js中。尝试替换以下代码

module.exports = function(app){

    exports.createJob = function(req, res){

        var job = new Job({created: Date.now});
        job.set('title', req.body.title);
        job.set('description', req.body.description);
        job.set('hours', req.body.hours);
        job.save(function(err){
            if (err) {
                alert(err);
            }
            else {
                alert('Job Posted Succesfully');
            }
        });

    }

};

exports.createJob = function(req, res){

        var job = new Job({created: Date.now});
        job.set('title', req.body.title);
        job.set('description', req.body.description);
        job.set('hours', req.body.hours);
        job.save(function(err){
            if (err) {
                alert(err);
            }
            else {
                alert('Job Posted Succesfully');
            }
        });

    };

并确保您发送的是响应,而不是发出警报。