2014-09-03 53 views
1

我有一個示例代碼,顯示結果並希望將結果轉換爲數組。我可以如何將貓鼬json結果轉換爲數組?

TranModel 
     .find({ quantityout: 1 }, 
         { _id: 0}) 
     .sort({ tag: 1 }) 
     .select('tag') 
     .populate('createdby') 
     .exec(function(err, data){ 
      if(err){ 
       res.json(err) 
      } else { 
       res.json(data) 
      } 
     }) 

結果

[ 
    { 
    "tag": "TH000001" 
    }, 
    { 
    "tag": "TH000006" 
    }, 
    { 
    "tag": "TH000009" 
    }, 
    { 
    "tag": "TH000011" 
    }, 
    { 
    "tag": "TH000014" 
    } 
] 

我需要轉換的結果喜歡這個

[ 
    "TH000001", 
    "TH000006", 
    "TH000009", 
    "TH000011", 
    "TH000014" 
] 

回答

6

你不能從貓鼬find查詢得到直接,但您使用管理輸出JavaScript Array.map功能得到你要的東西:

TranModel 
    .find({ quantityout: 1 }, 
      { _id: 0}) 
    .sort({ tag: 1 }) 
    .select('tag') 
    .exec(function(err, docs){ 
     docs = docs.map(function(doc) { return doc.tag; }); 
     if(err){ 
      res.json(err) 
     } else { 
      res.json(docs) 
     } 
    }) 

我拿出了populate調用,因爲在這裏沒有任何意義,因爲你在輸出中不包含createdBy

+0

謝謝#JohnnyHK,適合我。 – user2830412 2014-09-04 04:58:03