Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed):

angular
    .module('app')
    .factory('Employee', function($resource) {
        return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionName/:id",
        {apiKey: apiKey, dbName: dbName, collectionName: collectionName},
        { update: { method: 'PUT' } });
});

The add/edit form controller for creating/retrieving an employee looks like this:

if($stateParams.id === "add") {
    $scope.employee = new Employee();
} else {
    $scope.employee = Employee.get({id: $stateParams.id});
}

On the form, there is a Save button with the following function attached to it:

if($scope.employee._id) {
    $scope.employee.$update({id:$scope.employee._id});
} else {
    $scope.employee._id = $scope.employee.jmbg;
    $scope.employee.$save();
}

While the "Add" functionality works smoothly, updating an existing employee results in the following error:

400 Bad Request - Invalid object { "_id" : "000" , "jmbg" : "000" , "name" : "Bilbo" , "surname" : "Hagins" , "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5c575c577e5c575c57105d5153">[email protected]</a>" , "$promise" : { } , "$resolved" : true} - Document field names can't start with '$' (Bad Key: '$promise')

Even though my $scope.employee does contain these fields, this is the first time I've encountered such an issue. I have utilized similar functionalities in other projects without any errors, including one that uses the same MongoLab API backend.

Note that no configuration has been set up within my angular app.

Answer №1

Angularjs automatically includes $promise and $resolved when performing a PUT request.

Therefore, it is necessary to remove these attributes at the endpoint, as shown in the following example using express's router:

router.route('/contact/:id').put(function(req, res) {
    var contact = req.body;
    delete contact.$promise;
    delete contact.$resolved;
    // update the database
});

The reason behind why angularjs adds $promise and $resolved during a PUT request remains uncertain.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Bash JSON Variables to SQLite

I'm struggling to solve this issue - the SQL query that is generated is showing errors key="test" payload=$(gzip -ckqd ./temp.json.gz | jq -c . | sed 's/"/\\"/g') printf 'INSERT INTO my_table VALUES ("%s", "%s")' "$key" ...

"Troubleshooting a Node.js JWT issue in a React.js

I've been diving into backend development and recently created some small APIs. They all function perfectly in Postman, but I encountered an issue when attempting to execute this particular call const onSubmit = async () => { try { setIsL ...

Transforming a JSON object into a case class with a single field: a step-by-step guide

When dealing with Play 2.1, using reads to convert Json into objects is a common practice. However, it becomes tricky when working with case classes that have only one field. The usual method for multiple fields doesn't apply in this scenario as &apos ...

receiving a parsererror due to an assumed lack of data in the JSON

THE ISSUE My JSON data contains associative arrays that I extract and display on my webpage. Occasionally, one or more of the sub-arrays may be empty as part of normal operation. However, whenever an empty sub-array is encountered, it triggers a "parserer ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Empowering Components with React Hooks

I am currently in the process of transitioning from using class components to React hooks with the Context API. However, I am encountering an error and struggling to pinpoint the exact reason for it. Here are my Codes: // contexts/sample.jsx import React ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

Change events are not being received upon clicking the radio buttons

Hey friends, I'm trying to set up backbone events for when radio buttons are clicked. Here are the radio buttons I have: <p><label for="pays">Pays now</label><input id="pays" name="pays" type="radio" value="1" class="_100"/>&l ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

"Sequencing time with Postgres, manipulating views with Angular

I am encountering issues with displaying graphs in AngularJS. My backend is written in nodeJS and includes an aggregator as a buffer for data received from netdata, which is then inserted into the database using a cron job. Now, with a new client request, ...

After manipulating the array, Vue fails to render the input fields generated by the v-for directive

After setting the value externally, Vue component won't re-render array items. The state changes but v-for element does not reflect these changes. I have a component that displays items from an array. There are buttons to adjust the array length - &a ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Use jquery or javascript to align a button to the center

Can the vote button be centered in the script below? <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6352993.js"></script> <noscript><a href="http://polldaddy.com/poll/6352993/">This is a le ...

Persist the modified contenteditable data into a JSON file by utilizing PHP Ajax

I am currently working on making a webpage content editable using HTML 5 and saving the data in a JSON file for future use. Additionally, I would like to implement AJAX to load only the edited part of the page and have a PHP file modify the JSON file. An ...

Two jQuery scripts failing to cooperate

My website is built using jQuery 2.0.3 and bootstrap. I have implemented two different functions in jQuery, one for creating a dropdown menu and another for changing images on page load. $(document).ready(function() { //To display a random image eve ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Creating a three.js visualization of a cheerful X-Y coordinate graph

I am looking to generate a positive X-Y plane in mesh format using three.js. Additionally, I would like the ability to click on any intersection point and retrieve the coordinate values, resembling a graph paper layout. Design.prototype.mouseUp = functi ...