JS Data error: The attributes provided must include the property indicated by idAttribute - particularly with regards to hasMany relationships

Encountered Error:

The main key for my user model is username. The primary key for my routes is the routename. When my API returns JSONs, they are nested inside data:{} following jsonapi.org specifications. However, this structure differs from what js-data requires, as it expects the id attribute to be at the top level. To handle this discrepancy, I have been returning data.data in the afterFind function for 'users'. I attempted a similar approach for 'routes' but encountered challenges due to it being an array of routes. The console log output in beforeInject shows:

Result in beforeInject

Configuration Details:

  DS.defineResource({
    name: 'users',
    idAttribute: 'username',
    basePath: apiEndpoint,

    relations: {
        hasMany: {
            routes: {
                localField: 'routes',
                foreignKey: 'username'
            }
        }
    },
    // custom setting for this resource
    afterFind: function(resource, data, cb) {
        // implementing specific logic for "users"
        cb(null, data.data);
    }
});

DS.defineResource({
    name: 'routes',
    idAttribute: 'routename',
    basePath: apiEndpoint,
    cacheResponse: true,
    relations: {
        belongsTo: {
            users: {
                parent: true,
                localKey: 'username',
                localField: 'users'
            }
        }
    },
    beforeInject: function(resource, data) {
        // executing additional tasks specific to "users"
        console.log(data);
        return data.data.routes;
    }
});

Issue Arises During Attempt to Load Routes:

  resolve: {
            user: function($route, DS) {
                var username = $route.current.params.username;
                return DS.find('users', username).then(function(user) {
                    DS.loadRelations('users', user.username, ['routes']).then(function(user) {
                        console.log(user);
                    }, function(err) {
                        console.log(err);
                    });
                });
            }
        }

Answer №1

Not only is your information stored within a "data" category, but also under a "routes" category. So when locating the routes, you are attempting to insert something like:

{
  routes: [{
    // linked to a user
    username: 'john1337',
    // main identifier of a route
    id: 1234
  }]
}

but what you actually need to inject is:

[{
  username: 'john1337',
  id: 1
}]

Include an afterFindAll function on your routes resource to execute cb(null, data.data.routes).

You will either have to:

A) Integrate numerous "after" hooks to all your Resources or

B) Construct the deserialization in a way that it can be applied universally across all Resources. Maybe something similar to this concept?

DS.defaults.afterFind = function (Resource, data, cb) {
  cb(null, data.data[Resource.name])
};
DS.defaults.afterFindAll = function (Resource, data, cb) {
  cb(null, data.data[Resource.name])
};

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

The jqGrid displays a plus sign even when the subgrid is empty while using XML

I am utilizing jqGrid to display data with a subgrid in XML format. $("#UDFs").jqGrid({ ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' }, datatype: 'xmlstring', datastr: data, xmlReader: { root: "Respo ...

Choose the camera when utilizing the navigate.getUserMedia() function

I am currently utilizing the navigate.getUserMedia() method to record video on my mobile device and perform additional processing on it. However, at the moment, it is only capturing video using the front camera. How can I make it switch to the rear facing ...

Mongoose, Angular, and Express are not functioning properly when using the PUT method

I'm having trouble with implementing a basic edit function in my application. The delete and get functions are working fine, but I keep encountering a 500 error when trying to make a put request. I've attempted using findByIdAndUpdate and FindOne ...

Something is overriding the style created by makestyle material UI that I had implemented

How can I increase the importance of my makeStyles classes over default Material UI styles? Here is my code: import { createTheme, ThemeProvider } from '@mui/material/styles'; import { makeStyles, createStyles } from '@mui/styles'; co ...

Using Conditions in AngularJS: Choosing Between Callbacks and Promises in a Service

I am currently faced with a specific scenario where I am uncertain whether to implement a callback or a promise. As someone who is relatively new to promises and just beginning to grasp their concept, I want to avoid falling into any potential anti pattern ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

Error encountered: Unable to invoke module in AngularJS using Karma and Jasmine

Trying to implement unit testing for my AngularJS app using Karma, but encountering an issue with the module function. Error message: First Test encountered a declaration exception FAILED TypeError: Property 'module' of object [object Objec ...

Modify the style of a webpage through JavaScript

Need help with calling a JS event based on button presses and changing CSS font styling accordingly for each button? Check out the code snippet below: body { background-image: url("back2.jpg"); background-size: 100% 100%; } ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

Invoking AngularJS Function from Login Callback Script

Just getting started with angularjs and I have a logincallback function that is used for external login. This function returns the returnUrl, closes the externallogin pop up, and redirects back to the main page. function loginCallback(success, returnUrl) ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

The fade effect in React and material ui is consistent across both elements

I am facing an issue with a list where, for each list sibling onclick, a different element fades in with different text. The problem occurs when the fade effect starts once on siblings in the list and then disappears, not enabling again. This is the code: ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Transitioning away from bower in the latest 2.15.1 ember-cli update

I have been making changes to my Ember project, specifically moving away from using bower dependencies. After updating ember-cli to version 2.15.1, I transitioned the bower dependencies to package.json. Here is a list of dependencies that were moved: "fon ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

"Resolving problems with file uploads in Angular JS, Express JS, and Node

Need some assistance I'm still new to this and when it comes to file uploads, I found help from this resource - Below is my implementation. I've omitted certain parts to ensure readability of the post size. The main issue lies with the file upl ...