【问题标题】:Type error: TypeError: Cannot read property '_id' of undefined类型错误:TypeError:无法读取未定义的属性“_id”
【发布时间】:2015-12-01 16:46:52
【问题描述】:

我一直致力于使用 Yeoman 构建 Angular + Node 评论应用程序。

我无法解决错误“TypeError: Cannot read property '_id' of undefined”。

这是我的 /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);
  });
};

【问题讨论】:

  • 错误跟踪在哪里?

标签: generator yeoman-generator angular-fullstack


【解决方案1】:

查看您提供的代码,问题是req.bodyundefined

通过这样做:if (req.body._id),您仍在尝试访问未定义的属性。

正确的 if 语句是:

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

【讨论】:

  • 感谢您的回复。但这并没有解决问题。
  • 它解决了您报告的错误。现在,如果您需要帮助,请给我们一些详细信息。
猜你喜欢
  • 2020-09-03
  • 2013-09-03
  • 2022-07-27
  • 2022-09-23
  • 2019-09-13
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 2020-11-22
相关资源
最近更新 更多