我正在尝试显示Mongodb集合中的数据并根据值对其进行过滤。
问题是即使在使用管道过滤数据之后,如果只有一个条目满足条件,则会显示所有数据。我只想要满足所示条件的用户。这可能是一个逻辑错误,但我已经尝试了一切,但无法找到解决方案。
mongoDB结构如下(示例):
{
"_id": {
"$oid": "590b8bfb51123bed5e4b6dda"
},
"city": "Madrid",
"type": "admin",
"username": "admin",
"password": "admin",
"email": "admin",
"phone": 123,
"knowledgeLevel": [
{
"category": "media",
"_id": {
"$oid": "590b8bfb51123bed5e4b6ddf"
},
"subcategories": {
"javascript": 20,
"html": 16,
"css": 13,
"java": 10,
"net": 7,
"php": 0,
"c": 11,
"development": 10,
"network": 4,
"security": 0,
"patterns": 2,
"logic": 17,
"arithmetic": 9,
"testing": 1
}
},
{
"category": "code",
"_id": {
"$oid": "590b8bfb51123bed5e4b6dde"
},
"subcategories": {
"javascript": 0,
"html": 0,
"css": 0,
"java": 0,
"net": 0,
"php": 0,
"c": 0,
"development": 0,
"network": 0,
"security": 0,
"patterns": 0,
"logic": 0,
"arithmetic": 0,
"testing": 0
}
},
{
"category": "use",
"_id": {
"$oid": "590b8bfb51123bed5e4b6ddd"
},
"subcategories": {
"javascript": 0,
"html": 0,
"css": 0,
"java": 0,
"net": 0,
"php": 0,
"c": 0,
"development": 0,
"network": 0,
"security": 0,
"patterns": 0,
"logic": 0,
"arithmetic": 0,
"testing": 0
}
},
{
"category": "think",
"_id": {
"$oid": "590b8bfb51123bed5e4b6ddc"
},
"subcategories": {
"javascript": 0,
"html": 0,
"css": 0,
"java": 0,
"net": 0,
"php": 0,
"c": 0,
"development": 0,
"network": 0,
"security": 0,
"patterns": 0,
"logic": 0,
"arithmetic": 0,
"testing": 0
}
},
{
"category": "create",
"_id": {
"$oid": "590b8bfb51123bed5e4b6ddb"
},
"subcategories": {
"javascript": 0,
"html": 0,
"css": 0,
"java": 0,
"net": 0,
"php": 0,
"c": 0,
"development": 0,
"network": 0,
"security": 0,
"patterns": 0,
"logic": 0,
"arithmetic": 0,
"testing": 0
}
}
],
"__v": 0
}
我的管道如下(我认为问题出在过滤器函数中,它的作用是它通过用户对象运行并查找user.knowledgeLevel.media.java值并将其与内部的javalevel值进行比较HTML,如果它等于或大于该值,则返回它):
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'javafilter'
})
export class JavaFilter implements PipeTransform {
transform(users: any, javalevel: any): any{
if(javalevel === undefined) return users;
return users.filter(function(user){
for(let user of users){
for(let kn of user.knowledgeLevel){
if(kn.category==='media'){
if(kn.subcategories.java>=javalevel){
console.log(user);
return user;
}
}
}
}
})
}
}
我的表(我只发布表格行)生成的是这个:
<tr *ngFor="let user of users | javafilter:javalevel" >
<td id="center" class="col-md-4">{{user.email}}</td>
<td id="center" class="col-md-3">{{user.phone}}</td>
</tr>
javalevel值与上表中的HTML相同,如下所示:
<div id="java">
<div class="col-md-10"><h5>Java</h5></div>
<div class="col-md-2"><h5>{{javalevel}}</h5></div>
<input type="range" min="0" max="20" [(ngModel)]="javalevel" step="1" />
</div>
提前谢谢!
答案 0 :(得分:2)
因为您使用的是Array.filter
,所以删除第一个for-loop
,因为它们是相同的。
此外,使用Array.filter
时,您应该返回true / false,请参阅documentation。
return users.filter(function(user){
for(let kn of user.knowledgeLevel){
if(kn.category==='media'){
if(kn.subcategories.java>=javalevel){
console.log(user);
return true;
}
}
}
})