2017-09-26 52 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和猫鼬文件。我试图在快递文件中找到答案。 –

相关问题