2017-09-26 24 views
0

我是新來表達並試圖建立一個寧靜的api,通過其他屬性而不是id獲取元素。如何通過路由器快速獲取其他屬性的元素?

在我發現,他們通常會得到由ID元素的教程,示例代碼可能是:

router.route('/something/:something_id') 

    .get(function(req, res) { 
     Something.findById(req.params.something_id, function(err, something) { 
      if (err) 
       res.send(err); 

      res.json(something); 
     }); 
    }); 

和架構可能是這樣的:

var SomethingSchema = new Schema({ 
    name: String, 
    color: String 
}); 

但我試圖讓通過一些其他屬性,如

router.route('/something/:something_color') 

    .get(function(req, res) { 
     // get all somethings with color = something_color 
    }); 

回答

2

你需要學習mongodb和或mongoose,它實際上很直接。有Schema.find功能,它正是你想要做的。

router.route('/something/:something_color') 

.get(function(req, res) { 
    // get all somethings with color = something_color 
    Something.find({ color: req.params.something_color }, function(err, something) { 
     if (err) 
      res.send(err); 

     res.json(something); 
    }); 
}); 

我只是搜索的MongoDB表達對谷歌和第一頁,我發現這個教程:https://zellwk.com/blog/crud-express-mongodb/

希望它可以幫助

+0

非常感謝,我想我應該讀的MongoDB和貓鼬文件。我試圖在快遞文件中找到答案。 –

相關問題