Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected response to contain an array but got an object

So I'm new in Angular, and I've looked over various other solutions, but no one seemed to work for me. My app needs to take some data from mongodb database and show it to the client. The thing is I get

Error: [$resource:badcfg] Error in resource configuration for action query. Expected response to contain an array but got an object

Here is my SchoolCtrl.js on the client

app.controller('SchoolsCtrl', function($scope, SchoolResource) {
    $scope.schools = SchoolResource.query();
});

Here is my ngResource

app.factory('SchoolResource', function($resource) {
    var SchoolResource = $resource('/api/schools/:id', {id: '@id'}, { update: {method: 'PUT', isArray: false}});
    return SchoolResource;
});

This is my SchoolsController on the server

var School = require('mongoose').model('School');

module.exports.getAllSchools = function(req, res, next) {
    School.find({}).exec(function(err, collection) {
        if(err) {
            console.log('Schools could not be loaded: ' + err);
        }

        res.send(collection);
    })
};

I tried adding IsArray: true, tried adding [] after 'SchoolResource' in the resource, tried changing routes, nothing worked. I wanted to see what actually is returned, that the query complained is not array, so I turned it to string and this was the result:

function Resource(value) { shallowClearAndCopy(value || {}, this); }

I have no idea why it returns a function. Can anyone help me?

like image 687
nelfurion Avatar asked Jan 13 '15 20:01

nelfurion


1 Answers

That error message usually means your server is returning JSON representing a single object, such as:

{"some": "object", "with": "properties"}

when Angular is expecting JSON representing an array, like:

[ {"some": "object", "with": "properties"}, {"another": "object", "with": "stuff"} ]

Even if there is only a single result, query expects JSON for an array:

[ {"a": "single", "result": "object"} ]

You can verify this by simply loading your API call into the browser and checking it out. If there aren't square brackets around the whole JSON response, it isn't an array.

like image 125
Chris Bouchard Avatar answered Sep 23 '22 03:09

Chris Bouchard