简体   繁体   English

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

[英]MEAN Stack, MongoDB record creation not working

I am developing a MEAN stack application. 我正在开发MEAN堆栈应用程序。 I am trying to simply create a record in MongoDB from a form. 我试图从表单中简单地在MongoDB中创建一条记录。 I have verified in the debugger that the data binding is working between the view and the controller. 我已经在调试器中验证了视图和控制器之间的数据绑定是否有效。 In the server side controller code, checking the req.body before trying to save the record returns "undefined" (see below in the code). 在服务器端控制器代码中,在尝试保存记录之前检查req.body会返回“未定义”(请参见下面的代码)。 In the Angular controller, I have examined the "results" value in the callback when the announcement.$save function is executed and it shows the heading and details values to be populated as they should. 在Angular控制器中,我检查了当执行announcement。$ save函数时在回调中的“结果”值,它显示了要填充的标题和详细信息值。 However, the data is not persisted to the database and I get the following error: 但是,数据没有持久化到数据库,并且出现以下错误:

{ [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 } } }

What am I missing? 我想念什么? Here is my code: 这是我的代码:

The form in my html file: 我的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>

The angular route for this page partial is defined as: 此页面局部的角度路线定义为:

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

Here is my controller code: 这是我的控制器代码:

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 = '';
    });
  };
}

The REST API route is defined as: REST API路由定义为:

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

The server side controller (announcements-controller.js): 服务器端控制器(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);
  });
};

And finally, I am using this Mongoose model (Announcements.js) 最后,我正在使用此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);

How is configured your routes in Angular? 如何在Angular中配置路线? Are you passing the controller as 'AnnouncementsVm'? 您是否将控制器作为“ AnnouncementsVm”传递?

Have you tried to access the values of the ng-models announcementHeading and announcementDetails from the controller? 您是否尝试从控制器访问ng-models notificationHeading和announcementDetails的值?

Try to put 试穿

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

});

};

And check if you are getting the correct values 并检查您是否获得正确的值

Problem solved. 问题解决了。 I had not integrated the body-parser for the route so the request wasn't being populated correctly. 我没有为该路线集成车身解析器,因此该请求未正确填充。 Here is the updated ExpressJS route: 这是更新的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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM