将 req.body 属性复制到猫鼬模型中时出错



首先,我不得不说我是Angular和节点技术的新手。很抱歉我的无知。

当我尝试从版本视图中保存实体时,我收到此错误:"在路径"类别"处的值"[对象对象]"投射到 ObjectId 失败"。

好吧,我有这些代码:

.HTML:

<form class="form-horizontal" data-ng-submit="update()" novalidate>
  <fieldset>
    <div class="form-group">
      <label for="listaCat">Categoría:</label>
      <select id="listaCat" class="form-control" data-ng-Fmodel="notification.category" data-ng-options="c.name for c in listaCategorias track by c._id">
      </select>
    </div>
    <div class="form-group">
      <label class="control-label" for="name">Descripción</label>
      <div class="controls">
        <input type="text" data-ng-model="notification.name" id="name" class="form-control" placeholder="Descripción" required>
      </div>
    </div>
    <div class="form-group">
      <input type="submit" value="Guardar" class="btn btn-default">
    </div>
    <div data-ng-show="error" class="text-danger">
      <strong data-ng-bind="error"></strong>
    </div>
  </fieldset>
</form>`

角度控制器:

$scope.update = function() {
  var notification = $scope.notification;
  notification.$update(function() {
    $location.path('notifications/' + notification._id);
  }, function(errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};

服务器端控制器:

var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    Notification = mongoose.model('Notification'),
    _ = require('lodash');
exports.update = function(req, res) {
  var notification = req.notification;
  notification = _.extend(notification , req.body);
  notification.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(notification);
    }
  });
};

猫鼬模型:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var NotificationSchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Rellena la notificación',
    trim: true
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  category: {
    type: Schema.ObjectId,
    ref: 'Category'
  }
});
mongoose.model('Notification', NotificationSchema);
var CategorySchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Rellena la categoría',
    trim: true
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});
mongoose.model('Category', CategorySchema);

因此,如果我使用 WebStorm 在更新方法时在服务器控制器内调试,我可以看到 req.body 附带的每个属性格式良好,但在将 req.body 转换为通知猫鼬模型后:

notification = _.extend(notification , req.body);

类别属性不是模型,而是 ObjectId。似乎 lodash.extend 无法正常工作复杂属性。我已经尝试了许多其他克隆对象的方法,但没有成功。

最后我解决了它,在角度控制器中用这条线:

  notification.category = $scope.notification.category._id;
  notification.$update(function() {

无论如何,我认为这不是正确的方法。我想一定有一种方法可以将 req.body 属性复制到猫鼬模型中,而无需手动对复杂属性执行此操作。

提前非常感谢!

由于您正在使用AngularJS和ExpressJS,因此我建议您使用$resource该服务,该服务正是用于与其余API进行交互的。

**$resource**包含以下默认操作集:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

我在上面分享的链接中提供了很好的文档。

在您的情况下:我假设,http://localhost:300/notifications/:id,这可能是您要执行更新操作的 REST URL。

您可以创建自定义服务,例如:

var module = angular.module('myapp.services',['ngResource']);
module.factory('MyAppUpdateService',function($resource){
    return $resource('notifications/:id', 
    {
        id: '@id'
    },
    {
        'update': { method:'PUT' }
    }
);
});

现在,在您的角度应用程序控制器中,您可以将此服务作为依赖项注入,因此它可以在该 REST URL 中执行更新。

angular.module('myapp',['ngResource','myapp.services']);
angular.module('myapp').controller('MeetupsController',['$scope','$resource','$state','$location','MeetupUpdateService','socket',
                                                          function($scope,$resource,$state,$location, MyAppUpdateService){
$scope.updateMeetup = function(){
                $scope.updateService = new MyAppUpdateService();
                $scope.updateService.name = $scope.notification.name;
                .
                .
                .
$scope.updateService.$update({id:$scope.notification.category._id},function(result){  
                    $location.path("/meetup/")
                });
            }
})]);

所以这只是一个例子,如果你想要更全面的实现。看这里,我正在创造我自己的MEAN种子,我也在做同样的事情。如有疑问,请问。

最新更新