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

Encountered an error while attempting to load resource in Node.js

I'm currently working on a project utilizing Node js (Express...). Let me do my best to explain the issue I am encountering. My work is being done on localhost, and the main page of my index.html has buttons that lead to other pages when clicked. I c ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Ways to prevent false activation of functions due to changes and clicks

I have a text box and a clear button. When the user inputs something in the text box and then clicks out of it, a function called 'validate()' is triggered to perform an action. However, when I click the clear button instead and trigger another f ...

Troubleshooting the issue with Protractor/Jasmine test when browser.isElementPresent does not detect a class in the

As a newcomer to Jasmine testing, I've been facing some challenges while running my tests. Specifically, I have been struggling with my webdriver closing the browser before it can check the '.detailsColumn' element for expected results. Afte ...

What is the most efficient method for removing nested keys and their corresponding curly braces in a Python dictionary?

Currently, I have a JSON file loaded as a dictionary using json.loads: dict = { "Area":[ { "id": "aira-01", "vis": [ "menu" "hamburger" ] }, { "id": "aira-02" } My goal is to remove the entire key and value pair: "id": ...

I am encountering an issue where the msal-browser login process seems to be frozen at the callback

After successfully installing the msal-browser package, I am able to log in. However, I encounter an issue where the screen gets stuck at the callback URL with a code. The samples provided in the GitHub repository demonstrate returning an access token in ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Decoding JSON with various Tokens in C#

When I query the Klout API, I receive a response that contains the following fields: Name Score ScoreDeltas Day Change Week Change Month Change After creating classes in .NET and populating objects with JSON responses, everything functions properly. Ho ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Utilize Vue.js to send bound data to a click event

I am currently working with a v-for loop that iterates over data fetched from an API, setting the key as the ID of each object. My goal is to create a click event that captures the v-bind:key value of the clicked element. This will allow me to locate all t ...

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

What is the most effective way to update the React state based on an if-else condition within a

I am facing an issue where I have a component in my project that needs to update the parent state when clicked, but there is an if-else condition causing the state not to update in the parent component. In my project, I have two boxes with an if-else cond ...

Tips for renaming property names during JSON serialization in asp.Net

In my MVC Web API Controller, there is a method that I have exposed: [HttpPost] public JsonResult<CustomClass> Details(RequestClass request) { var encoding = Encoding.GetEncoding("iso-8859-1"); var settings = new ...

React.js encountered an error: Objects cannot be used as a React child (found: object containing keys {type, data})

My current project involves displaying MySQL data in a table using Node.js and React.js. However, I keep encountering the following error: Error: Objects are not valid as a React child (found: object with keys {type, data}). If you meant to render a colle ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...