2015-12-01 125 views
0

我一直在使用Yeoman構建一個Angular + Node註釋應用程序。類型錯誤:TypeError:無法讀取未定義的屬性'_id'

我無法解決錯誤「TypeError:無法讀取未定義的屬性'_id'」。

這是我/api/comment/index.js文件

'use strict'; 
 

 
var express = require('express'); 
 
var controller = require('./comment.controller'); 
 
var auth = require('../../auth/auth.service'); 
 
var router = express.Router(); 
 

 
router.get('/:id', controller.show); 
 
router.put('/:id', controller.update); 
 
router.patch('/:id', controller.update); 
 
router.get('/', controller.index); 
 
router.post('/', auth.isAuthenticated(), controller.create); 
 
router.delete('/:id', auth.isAuthenticated(), controller.destroy); 
 
    
 
module.exports = router;

這是我comment.controller.js文件

/ Gets a single Comment from the DB 
 
exports.show = function(req, res) { 
 
    Comment.findByIdAsync(req.params.id) 
 
    .then(handleEntityNotFound(res)) 
 
    .then(responseWithResult(res)) 
 
    .catch(handleError(res)); 
 
}; 
 

 
// Updates an existing Comment in the DB 
 
exports.update = function(req, res) { 
 
    if (req.body._id) { 
 
    delete req.body._id; 
 
    } 
 
    Comment.findByIdAsync(req.params.id) 
 
    .then(handleEntityNotFound(res)) 
 
    .then(saveUpdates(req.body)) 
 
    .then(responseWithResult(res)) 
 
    .catch(handleError(res)); 
 
}; 
 

 
// Deletes a Comment from the DB 
 
exports.destroy = function(req, res) { 
 
    Comment.findByIdAsync(req.params.id) 
 
    .then(handleEntityNotFound(res)) 
 
    .then(removeEntity(res)) 
 
    .catch(handleError(res)); 
 
}; 
 

 
// Get list of comments 
 
exports.index = function(req, res) { 
 
    Comment.loadRecent(function (err, comments) { 
 
    if(err) { return handleError(res, err); } 
 
    return res.json(200, comments); 
 
    }); 
 
}; 
 
    
 
// Creates a new comment in the DB. 
 
exports.create = function(req, res) { 
 
    // don't include the date, if a user specified it 
 
    delete req.body.date; 
 
    
 
    var comment = new Comment(_.merge({ author: req.user._id }, req.body)); 
 
    comment.save(function(err, comment) { 
 
    if(err) { return handleError(res, err); } 
 
    return res.json(201, comment); 
 
    }); 
 
};

+0

哪裏錯誤跟蹤? –

回答

0

Loo國王在你提供的代碼,問題是req.bodyundefined

通過做:if (req.body._id),你仍然試圖訪問未定義的屬性。

正確的if語句應該是:

if (req.body && req.body._id) { 
    // do stuff 
} 
+0

感謝您的回覆。但它沒有解決問題。 –

+0

它解決了你報告的錯誤。現在,如果你需要幫助,請給我們一些細節。 –

相關問題