MongoDB的+ AngularJS:通过resourceProvider在更新_id空AngularJS、MongoDB、_id、resourceProvider

2023-09-13 04:05:46 作者:万撸男神

我使用的MongoDB(Rails的3 + Mongoid)和角JS。

I am using Mongodb (Rails 3 + Mongoid) and Angular JS.

在我的数据库,我有一个集合用户持有对象地址的数组。我想更新数组中的一个地址字段,但是当我发送更新请求(采用了棱角分明的 resourceProvider ),所有的 _id 的角度发送到我的服务器是 {} (即空的),所以我结束了重复而非修改。

In my db, I have a collection users which holds an array of objects addresses. I am trying to update the fields on an address in the array, but when I send the update request (using Angular's resourceProvider), all the _id that Angular sends to my server is "{}" (i.e. empty), so I end up with duplication instead of modification.

$ scope.user.addresses持有非空ID和看起来像这样:

[{_id:{$oid:"123431413243"}, text:"123 fake", cat:1},{_id:{$oid:"789789078907890}, text:"789 test", cat:7},...]

的PUT请求主体持有空ID和看起来像这样:

{"_id":{}, "user":{"addresses_attributes":[{"_id":{}, "text":"123 fake", "cat":"1"},{"_id":{}, "text":"789 test", "cat":"7"},...]}}

角JS code

myApp.factory('Users', ['$resource', function ($resource) {
    return $resource( '/users/:id.json', {id:0}, {update: {method:'PUT', _method:'PUT'}} );
}]);

myApp.controller('UsersCtrl', function ($scope, Users) {
    $scope.save = function () {
        $scope.user.$update({}, {user:$scope.user});
    };
});

你有任何想法,为什么这是什么,我能做什么呢?

Do you have any idea why this is and what I can do about it?

推荐答案

它看起来像有两个选项:覆盖角度JS的转型行为或覆盖Mongoid的序列化行为

It looks like there are two options here: override Angular JS’s transformation behavior or override Mongoid’s serializing behavior.

选项1:重写Mongoid的序列化行为

添加一个文件覆盖 serializable_hash Mongoid ::文件

# config/initializers/override_mongoid_serializable_hash.rb
module Mongoid
  module Document   

    def serializable_hash(options={})
      attrs = super
      attrs['id'] = attrs.delete('_id').to_s
      attrs
    end

  end
end

不要简单地试图重写 as_json 方法,因为(出于某种原因),您定义该功能仅适用于对象的新行为,在其上被称为(用户),而不是在包含对象(地址)。

Don't simply try to override the as_json method because (for some reason) the new behavior that you define for that function will only apply to the object on which it is called (User), not on the included objects (Addresses).

选项2:重写角JS的转化行为

使用在这个答案的说明: http://stackoverflow.com/a/12191613/507721

Use the instructions in this answer: http://stackoverflow.com/a/12191613/507721

在总之,在调用 myApp.config()在角JS的应用程序,设置 $ httpProvider.default自己的函数值.transformRequest 。从上面链接的回答的例子是如下:

In short, in the call to myApp.config() in your Angular JS app, set your own function value for $httpProvider.default.transformRequest. The example from the answer linked above is as follows:

var myApp = angular.module('myApp');

myApp.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});

以上函数的主体是由你。但是转换是必要的。

The body of the foregoing function is up to you. Transform it however is necessary.