2014-10-14 7 views
0

내가 ExpressJS, NodeJS와 몽구스와 JSON의 API 건물입니다 :NodeJS/몽구스 필터 JSON

입력 -> 번호 :

[{"_id":"B443U433","date":"2014-08-12","reference":"azerty","file":"087601.png"," 
....:. 
{"_id":"HGF6789","date":"2013-09-11","reference":"azerty","file":"5678.pnf"," 
... 

:

app.get('/folder/:id', function (req, res){ 
    return Cars.find({reference: req.params.id}, function (err, product) { 
    if (!err) { 
     console.log(product); 
     return res.send(product); 
    } else { 
     return console.log(err); 
    } 
    }); 
}); 

이 아니라 JSON을 보여줍니다 방금 에 _id을 JSON에 표시하려고하므로 많은 데이터가있을 때 좋습니다.

어떻게 할 수 있습니까? 필터 같은 것?

+0

(이 몽고 쉘 명령과 동일입니다) 예). 나는 몽구스와 몽고 (mongoose)를 사용하고 있습니다. – Jose

답변

0

당신은

뭔가이 같은 ID를 얻기 위해 객체 당신의 "제품"을 반복 할 것이다 : (면책 조항 :이 테스트를하지 않은 경우)

app.get('/folder/:id', function (req, res){ 
    return Cars.find({reference: req.params.id}, function (err, product) { 
    if (!err) { 
     console.log(product); 

     var ids = new Array(); 
     for(var i = 0; i < product.length; i++){ 
      ids.push(product[i]._id); 
     } 
     return res.send(JSON.stringify(ids)); 
    } else { 
     return console.log(err); 
    } 
    }); 
}); 

--edit

또한 "제품"은 이미 JSON 문자열 일 수 있습니다. 반복하기 전에 구문 분석 할 수 있습니다.

product = JSON.parse(product); 
+0

대단히 감사합니다. – Jose

2

당신은 selectlean에 체인 호출 당신이 문서는 쿼리있어에서 원하는 바로 필드를 검색 할 수 있습니다

app.get('/folder/:id', function (req, res){ 
    return Cars.find({reference: req.params.id}).select('_id').lean().exec(
    function (err, product) { 
     if (!err) { 
     console.log(product); 
     return res.send(product); 
     } else { 
     return console.log(err); 
     } 
    }); 
}); 
0

다른 답변에 해당하지만 난 그게 데이터를 제한하기 위해 더 나은 생각을 이 같은 몽구스 : 난 그냥 응답 (안 날짜 또는 파일에 _ID 갖고 싶어) 나는 app.get (건물 오전 JSON에서

app.get('/folder/:id', function (req, res){ 
    Cars.find({reference: req.params.id} ,{ _id : true } ,function (err, product) { 
     if (!err) { 
      console.log(product); 
     } else { 
      console.log(err); 
     } 
    }); 
});