我正在使用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);
});
};
不太清楚錯誤是什麼。
我對MAN堆棧一無所知,但是我知道angular,express和nodejs。和原因的javascript ;-)錯誤消息告訴你,該req.question是null或undefined。我不知道足夠100%肯定。但我認爲貓鼬中間件不能正確地將問題對象添加到請求中。是否有錯誤日誌?或者你忘記添加貓鼬中間件;-)或者貓鼬使用另一個變量req.xyz? –
'req.question'在哪裏設置? – mscdex
@mscdex他使用mongose中間件。我假設這個中間件從mongodb中讀取一個對象,這個對象是由他提供的id:id來提供的(...。然後這個對象被豐富了questionSchema.methods中定義的方法添加到請求中。通過執行一個console.dir(req);作爲函數exports.upvoteQuestion中的第一行 –