I'm having a little trouble trying to retrieve Mongoose.count values from a function in my back end API within my mean.js application. Everything is routed correctly as far as I can see, and seems to be working absolutely fine until I get to the front end angular code and try to retrieve the data from the API via a service and $resource.
Here's my back end API function to retrieve the count of listings in a particular category, where the category is passed in correctly as parameter.
exports.getListingCountForSpecificCategory = function(req, res, next, category) {
Listing.count({
category: category,
quantityAvailable: { $gt: 0 },
listingActive: true
}, function(err, count){
if(err) {
console.log(err);
} else {
console.log(category + ': ' + count);
res.jsonp(count);
}
});
};
This runs correctly and within the console.log()
console.log(category + ': ' + count);
The category count is returned correctly. So, everything working correctly!
Until I get to retrieving the count value with angular on the front end. Here's the function I've written:
$scope.listingsCount = function(category) {
$scope.catCount = Listings.listingsCategoryCount.query({
category: category.alias
});
$scope.catCount.$promise.then(function(count){
category.listingCount = count;
});
};
When this function is run and the category object is passed into it, instead of it retrieving the count value e.g. 14, it seems to retrieve a resource promise object instead, with the count value nowhere to be seen. I've looked over the code a few times and can't for the life of me figure out why.
Here's the service I'm using, just in case you need to see it.
listingsCategoryCount: $resource('listingscount/:category', {
category: '@_category'
}, {
query: {
method: 'GET',
isArray: false
}
}),
It's a mystery to me why the count value isn't being returned. I may be going about this incorrectly of course. Any help would be greatly appreciated.
Thanks
https://docs.angularjs.org/api/ngResource/service/$resource:
On success, the promise is resolved with the same resource instance or collection object, updated with data from server.
Change this: res.jsonp(count);
to res.jsonp({ count: count });
and it should work: you'll get a Resource
object with property count
.