MEAN Stack,MongoDB 记录创建不起作用

Posted

技术标签:

【中文标题】MEAN Stack,MongoDB 记录创建不起作用【英文标题】:MEAN Stack, MongoDB record creation not working 【发布时间】:2016-03-19 08:16:59 【问题描述】:

我正在开发一个 MEAN 堆栈应用程序。我正在尝试从表单中简单地在 MongoDB 中创建一条记录。我已经在调试器中验证了数据绑定在视图和控制器之间工作。在服务器端控制器代码中,在尝试保存记录之前检查 req.body 会返回“未定义”(参见下面的代码)。在 Angular 控制器中,我检查了在执行 notice.$save 函数时回调中的“结果”值,它显示了要填充的标题和详细信息值。但是,数据没有保存到数据库中,我收到以下错误:

 [ValidationError: Announcement validation failed]
  message: 'Announcement validation failed',
  name: 'ValidationError',
  errors:
    details:
       [ValidatorError: Path `details` is required.]
        properties: [Object],
        message: 'Path `details` is required.',
        name: 'ValidatorError',
        kind: 'required',
        path: 'details',
        value: undefined ,
     heading:
       [ValidatorError: Path `heading` is required.]
        properties: [Object],
        message: 'Path `heading` is required.',
        name: 'ValidatorError',
        kind: 'required',
        path: 'heading',
        value: undefined   

我错过了什么?这是我的代码:

我的html文件中的表单:

  <form ng-submit="AnnouncementsVm.createAnnouncement()">
    <fieldset class="form-group">
      <label for="heading">Heading:</label>
      <textarea class="form-control" id="heading" rows="1"
        ng-model="AnnouncementsVm.announcementHeading"></textarea>
    </fieldset>
    <fieldset class="form-group">
      <label for="details">Details:</label>
      <textarea class="form-control" id="details" rows="3"
        ng-model="AnnouncementsVm.announcementDetails"></textarea>
    </fieldset>

    <p><input type="submit" value="Submit →"><p>
  </form>

此页面部分的角度路径定义为:

  $routeProvider.
    when('/announcements', 
      templateUrl: '/views/partials/announcements.html',
      controller: 'Announcements.Controller',
      controllerAs: 'AnnouncementsVm'
    );

这是我的控制器代码:

angular.module('app').
  controller('Announcements.Controller', AnnouncementsCtrl);

function AnnouncementsCtrl($log, $resource) 
  $log.debug('Executing AnnouncementsCtrl');
  var vm = this;
  var Announcement = $resource('/api/announcements');

  Announcement.query( function(results) 
    vm.announcements = results;
  );

  vm.announcements = [];

  vm.createAnnouncement = function() 
    var announcement = new Announcement(
      heading: vm.announcementHeading,
      details: vm.announcementDetails
    );
    announcement.$save( function(result) 
      vm.announcements.push(result);
      vm.announcementHeading = '';
      vm.announcementDetails = '';
    );
  ;

REST API 路由定义为:

app.post('/api/announcements', announcementsController.create);

服务器端控制器(announcements-controller.js):

'use strict';

var Announcement = require('../models/Announcement.js');

module.exports.create = function(req, res) 
  var announcement = new Announcement(req.body);
  console.log(req.body); // returns "undefined"
  announcement.save( function(err, result) 
    if (err) console.log(err);
    console.log('Save Announcement Result: ' + result);
    res.json(result);
  );
;

module.exports.list = function(req, res) 
  Announcement.find(, function (err, results) 
    if (err) throw err;
    res.json(results);
  );
;

最后,我正在使用这个 Mongoose 模型 (Announcements.js)

'use strict';

var mongoose = require('mongoose');

var AnnouncementSchema = new mongoose.Schema(
  heading: type: String, required: true,
  details: type: String, required: true,
  image: type: String, required: false
);

module.exports = mongoose.model('Announcement', AnnouncementSchema);

【问题讨论】:

【参考方案1】:

如何在 Angular 中配置您的路由?您是否将控制器作为“AnnouncementsVm”传递?

您是否尝试过从控制器访问 ng-models 的announcementHeading 和announcementDetails 的值?

试着放

vm.createAnnouncement = function() 
 $log.log(vm.announcementHeading);
 $log.log(vm.announcementDetails);

);

;

并检查您是否得到正确的值

【讨论】:

路由定义如下:`when('/announcements', templateUrl: '/views/partials/announcements.html', controller: 'Announcements.Controller', controllerAs: 'AnnouncementsVm' )。我在调试器中检查了 vm.announcementHeading 和 vm.announcementDetails 的值,得到了我期望的值。我使用 $log 得到相同的结果【参考方案2】:

问题解决了。我没有为路由集成 body-parser,所以请求没有被正确填充。这是更新后的 ExpressJS 路由:

'use strict';

var bodyParser = require('body-parser');
var path = require('path');
var announcementsController = require('../controllers/announcements-controller.js');

module.exports = function(app) 

  // create application/json parser
  var jsonParser = bodyParser.json();

  // create application/x-www-form-urlencoded parser
  var urlencodedParser = bodyParser.urlencoded( extended: false );

  app.get('/', function(req, res) 
    res.sendFile(path.join(__dirname, '../../client/views/index.html'));
  );

  // REST API
  app.get('/api/announcements', announcementsController.list);
  app.post('/api/announcements', jsonParser, announcementsController.create);
;

【讨论】:

以上是关于MEAN Stack,MongoDB 记录创建不起作用的主要内容,如果未能解决你的问题,请参考以下文章

在 MEAN Stack 应用程序中从 mongo db 检索数据

MongoDB Auth无法在Bitnami MEAN Stack Image上找到用户名

如何使用特定集合 Mongoose-Express-Mongodb (MEAN STACK)

部署 MEAN Stack 应用程序,托管问题

(MEAN STACK)后端在我提交表单时将objectId和__v:0保存在mongodb中

_.extend 忽略 MEAN Stack 中的一个属性