Mongodb + AngularJS: _id empty in update via resourceProvider -


i using mongodb (rails 3 + mongoid) , angular js.

in db, have collection users holds array of objects addresses. trying update fields on address in array, when send update request (using angular's resourceprovider), _id angular sends server "{}" (i.e. empty), end duplication instead of modification.

$scope.user.addresses holds non-blank ids , looks this:

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

the put request body holds empty ids , looks this:

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

angular 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 have idea why , can it?

it looks there 2 options here: override angular js’s transformation behavior or override mongoid’s serializing behavior.

option 1: overriding mongoid's serializing behavior

add file override serializable_hash on mongoid::document.

# 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 

don't try override as_json method because (for reason) new behavior define function apply object on called (user), not on included objects (addresses).

option 2: overriding angular js's transforming behavior

use instructions in answer: https://stackoverflow.com/a/12191613/507721

in short, in call myapp.config() in angular js app, set own function value $httpprovider.default.transformrequest. example answer linked above 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 foregoing function you. transform necessary.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -