簡體   English   中英

將req.body屬性復制到Mongoose模型時出錯

[英]Error copying req.body properties into Mongoose Model

首先,我必須說我是Angular和Node技術的新手。 非常抱歉,我的無知。

當我嘗試從版本視圖保存實體時收到此錯誤:“在路徑“類別”中,值“ [對象對象]”的對象轉換失敗。

好吧,我有以下代碼:

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的更新方法在Server控制器內部進行調試,則可以看到req.body帶有正確形成的每個屬性,但是在將req.body轉換為Notification Mongoose Model之后,使用了:

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

category屬性不是Model,而是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種子,並且我正在做同樣的事情。 如有疑問,請詢問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM