【问题标题】:Resource object returned instead of Mongoose.count value返回资源对象而不是 Mongoose.count 值
【发布时间】:2016-02-16 03:50:03
【问题描述】:

我在尝试从 mean.js 应用程序的后端 API 中的函数检索 Mongoose.count 值时遇到了一点麻烦。据我所知,一切都正确路由,并且似乎工作得非常好,直到我到达前端 Angular 代码并尝试通过服务和 $resource 从 API 检索数据。

这是我的后端 API 函数,用于检索特定类别中的列表计数,其中类别作为参数正确传递。

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);
        }
    });
}; 

这在 console.log() 中正确运行

console.log(category + ': ' + count);

正确返回类别计数。所以,一切正常!

直到我在前端使用 angular 检索计数值。这是我写的函数:

$scope.listingsCount = function(category) {
    $scope.catCount = Listings.listingsCategoryCount.query({
        category: category.alias
    });

    $scope.catCount.$promise.then(function(count){
        category.listingCount = count;
    });
};

当此函数运行并将类别对象传递给它时,而不是检索计数值,例如14,它似乎取而代之的是检索资源承诺对象,而计数值无处可见。我已经查看了几次代码,但终生无法弄清楚原因。

这是我正在使用的服务,以防万一您需要查看。

listingsCategoryCount: $resource('listingscount/:category', {
    category: '@_category'
}, {
    query: {
        method: 'GET',
        isArray: false
    }
}),

为什么不返回计数值对我来说是个谜。当然,我可能会错误地处理这个问题。任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: javascript angularjs node.js mongoose meanjs


    【解决方案1】:

    https://docs.angularjs.org/api/ngResource/service/$resource:

    成功后,promise 将使用相同的资源实例或集合对象解析,并使用来自服务器的数据进行更新。

    将这个:res.jsonp(count); 更改为 res.jsonp({ count: count });,它应该可以工作:你会得到一个带有属性 countResource 对象。

    【讨论】:

    • 非常感谢,它成功了!假设它也有点道理。我的一个沉闷的时刻:)。再次感谢
    猜你喜欢
    • 2014-11-28
    • 2015-07-10
    • 2017-10-06
    • 1970-01-01
    • 2021-09-18
    • 2019-10-22
    • 2012-09-28
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多