2012-06-17 5 views
0

나는 이것을 수행하는 방법이 없으므로 조언이 필요합니다. "정의되지 않은"-NodeJS + MongoDB : 특정 조건의 find()

나는 check_stain이 확인 된 경우, 다음 req.body.check_stain "의"그렇지 않으면 할 수 있도록 간단한에 데이터를 제출 보내
<input type="checkbox" class="checkbox" id="check_stain"> 
<input type="checkbox" class="checkbox" id="check_black"> 
<input type="checkbox" class="checkbox" id="check_titan"> 
<input type="checkbox" class="checkbox" id="check_special"> 

: 나는 4 확인란과 양식을 가지고있다.

{... 
    "stain": "false", 
    "black": "true", 
    "titan": "false", 
    "special": "true", 
...} 

값이 단순 문자열 : 내 DB에

나는 이러한 스키마를 포함하는 모든있는 여러 개체에 수집 "회사"를 보유하고 있습니다. 그래서, 나는 지정된 체크 박스가 true (on) 인 모든 객체를 가져야하지만 nones (undefined) 인 객체는 포함하지 않아야한다. 즉, 간단한 검색 알고리즘을 만들고 싶습니다. 예를 들어 보겠습니다. check_stain을 확인하면 얼룩이 "true"인 모든 객체를 가져와야합니다. 다른 값은 "true"/ "false"(중요하지 않음) 일 수 있습니다. check_stain과 check_black을 선택하면 얼룩이있는 객체가 & black = "true"이고 다른 필드는 관심이 없습니다.

나는 항상 같은 코드를 찾습니다

collection.find({ %my-condition% } ,function(err, companies) { 
    companies.each(function(err, company){ 
     //do smth with found 
    }); 
}); 

하지만 조건을 찾기 위해 작성하는 방법을 모른다. 나는 $ 또는 연산자를 요청해야한다고 생각한다. 나는 문서를 읽었지 만 나는 아직도 그것을 얻을 수 없다. 감사. UPDATE

는 예를 들면 다음과 같습니다

if (req.body.sort_query == 'req-steel') { 
var condition = {} 
if (req.body.check_stain == "on") {condition['stain'] = 'true';} 
if (req.body.check_black == "on") {condition['black'] = 'true';} 
if (req.body.check_titan == "on") {condition['titan'] = 'true';} 
if (req.body.check_other == "on") {condition['special'] = 'true';} 
for (var i in condition) { 
    if (condition[i] != "true") { 
     delete condition[i]; 
    } 
} 
var companies_list = new Array(); 
collection.find(condition, function (err, companies) { 
    companies.each(function (err, company) { 
     //do smth 
    }); 
}); 
}; 
+0

문제가있어 허, 그건 내 문제의 해결책이 될 것 같다? 사실 인 키로 객체를 만들고 다른 객체는 그대로 둡니다. – noob

+0

잘 모르겠습니다. 어디에서 collection.insert()를 사용하여 데이터베이스에 새 객체를 작성해야합니까? 내가 얻은 것처럼 요청을 찾는 매개 변수로이 객체를 보내거나 무엇을 제안할까요? – f1nn

+0

'stain'은''true '''이어야합니다 :: collection.find ({stain : "true"})''stain'과'black''은''true''이어야합니다''collection.find ({stain : " true ", black :"true "})' – noob

답변

1

흑인과 얼룩에 해당 :

var condition = { 
    "stain": "false", 
    "black": "true", 
    "titan": "false", 
    "special": "true", 
} 

for (var i in condition) { 
    if (condition[i] != "true") { 
     delete condition[i]; 
    } 
} 

collection.find(condition ,function(err, companies) { 
    companies.each(function(err, company){ 
     //do smth with found 
    }); 
}); 

Live condition DEMO

+0

감사합니다. 잠시 후 코드를 살펴 보겠습니다. 나는 여전히 어떻게 작동하는지 알 수 없다 ... – f1nn

+0

조건 개체에서 참이 아닌 모든 키를 제거하기 만하면된다. – noob

+0

내 게시물을 업데이트했습니다. 여기에 제가 작성한 코드가 있습니다. 나는 내 손가락을 넘었고 그것을 시작했습니다 :) 허, 제대로 작동하는 것 같습니다 :) 대단히 감사합니다! – f1nn

관련 문제