在前端过滤MongoDB数据

时间:2017-04-12 08:45:12

标签: angularjs node.js mongodb mongoose

我对MongoDb几乎没有任何问题。我有2个集合:拍卖和用户。在“用户”我显然存储用户(邮件,名称等)在拍卖我存储产品(creationdate,createdBy,FollowedBy,Invitations,image)。现在,我想在每个用户的仪表板中显示他所遵循的产品(当他点击按钮时,他的名字存储在“”FOllowedBy“中)。如果我必须在后端过滤,一切都很清楚,相反,我想从DB加载所有数据,然后用angularJs过滤前端。

使用像created这样的简单字段很简单:如果我有一个名为“Alex”的用户(例如),我只能在创建时与Alex(或其他所有用户)匹配时显示数据。但同样的事情不适用于像“FollowedBy”这样的数组字段。如果在产品“表格”中创建:“Mark”,FollowedBy:“Alex”和“Jack”,我可以轻松过滤所有产品以仅显示Mark的产品,但我不明白如何仅显示其后的产品亚历克斯,因为这个字段是一个数组。

这是我的后端路线。

           app.get('/api/dashboard', function (req, res) {

    AllAuctions
        .find({}, function (err, auctions) {
            if (err)
                res.send(err);
            console.log(auctions);
            res.send(auctions);

        });
});

我用$ http加载它与angularJs:

         $http.get('/api/dashboard').then(function (AllAuctions) {
           $scope.allauctions = AllAuctions.data;

       });

如果我必须过滤“createdBy”字段,我可以这样做:

           <div class="panel panel-default" >
    <div class="panel-heading">My Auctions</div>
    <div class="panel-body">
        <ul class="list-group" ng-repeat="allauction in allauctions">
            <li class="list-group-item" ng-show="allauction.createdBy=='Alex'">
                    <img ng-src="{{allauction.imgUrl}}">
                    <div class="title"> {{allauction.title}} </div>

</li>
</ul>
</div>
</div>

但我不明白如何过滤这样的字段:

                 FollowedBy: [
                      Shelly.name,
                      Dario.name
                 ]

仅显示达里奥所遵循的产品。

1 个答案:

答案 0 :(得分:1)

如果您想在html中执行此操作,可以执行类似

的操作
ng-show="allauction.FollowedBy.indexOf('Alex')>=0"

然而,当你有多个过滤器时,它将很快成为硬核。您应该在javascript中定义一个过滤函数,它将计算一个过滤的数组,您可以在其上执行简单的ng-repeat。或者您也可以在您的allauction对象中添加一个标志,并根据此标志执行ng-if / ng-show。例如:

function updateFilteredData()
{
    $scope.filteredData = [];
    for(var i = 0; i< $scope.allauction; i++)
    {
         var auction = $scope.allauction[i];
         if(auction.createdBy !== currentUser.name) //I assume currentUser is json object for your Alex user
             continue;
         if($scope.followByFilter && auction.FollowedBy.indexOf($scope.followByFilter) < 0)
              continue; //I assume followByFilter is a string containing the name of a follower you are trying to filter

         $scope.filteredData.push(auction);
    }

}

您需要在$ http get中调用此函数,并且每次过滤条件都会更改(例如:followByFilter名称更改...)。 你应该对filteredData数组进行ng-repeat而不是allauction。

相关问题