2015-05-23 79 views
2

我正在使用MEAN堆棧用於我的應用程序,並且我在每個問題的應用程序中都有一個upvote節,試圖upvote一個問題TypeError: Cannot read property 'upvote' of undefined。我的路線文件是這樣的:TypeError:無法讀取屬性'upvote'中的未定義堆棧

routes.js

app.put('/api/questions/:id/upvote', questions.upvoteQuestion); 

Question.js(型號)

var questionSchema = mongoose.Schema({ 
    question: {type:String, required:'{PATH} is required!'}, 
    category: [String], 
    upvotes: {type: Number, default: 0}, 
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }], 
    author: String 
}); 

questionSchema.methods.upvote = function(cb) { 
    this.upvotes += 1; 
    this.save(cb); 
}; 

questions.js(控制器)

exports.upvoteQuestion = function(req, res, next) { 
    req.question.upvote(function(err, question){ 
     if (err) { return next(err); } 
     res.json(question); 
    }); 
}; 

不太清楚錯誤是什麼。

+0

我對MAN堆棧一無所知,但是我知道angular,express和nodejs。和原因的javascript ;-)錯誤消息告訴你,該req.question是null或undefined。我不知道足夠100%肯定。但我認爲貓鼬中間件不能正確地將問題對象添加到請求中。是否有錯誤日誌?或者你忘記添加貓鼬中間件;-)或者貓鼬使用另一個變量req.xyz? –

+0

'req.question'在哪裏設置? – mscdex

+0

@mscdex他使用mongose中間件。我假設這個中間件從mongodb中讀取一個對象,這個對象是由他提供的id:id來提供的(...。然後這個對象被豐富了questionSchema.methods中定義的方法添加到請求中。通過執行一個console.dir(req);作爲函數exports.upvoteQuestion中的第一行 –

回答

-1

你試圖參考upvotes作爲問題的屬性,如果你改變問題是:

question: {type:String, required:'{PATH} is required!', upvotes: {type: Number, default: 0}} 

你可以參考其與此: req.question.upvote

然後更改給予好評的方法來此第二行:

questionSchema.methods.upvote = function(cb) { 
    this.question.upvotes += 1; 
    this.save(cb); 
}; 

,因爲它是現在定義,upvotes是questionSchema的屬性,如果這是你愛民什麼g因爲你不能把它稱爲問題的屬性。

雖然我沒有與貓鼬合作過。

+0

即使這樣也不會工作AFAIK。 – SarathMS

相關問題