nelfurion
nelfurion

Reputation: 141

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?

Upvotes: 5

Views: 8468

Answers (2)

Tabula Rasa
Tabula Rasa

Reputation: 1

It happened to me too, but then I printed the object in the console and found out that there was something like this:

{ options:{....},results:[ ...the Array I was looking for... ]}

so all you need to do there is

res.send(collection.results);

I hope this helps

Upvotes: 0

Chris Bouchard
Chris Bouchard

Reputation: 805

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.

Upvotes: 5

Related Questions