节点& Mongoose - 点击链接后加载正确的集合

时间:2016-12-02 13:27:04

标签: node.js mongodb express collections mongoose

我需要帮助!!我有这段代码:

router.get("/campgrounds", function(req,res) {
    Campground.find({}, function(err, campgrounds) {
        if(err) {
            console.log(err);
        } else {
            res.render("campgrounds/index", {campgrounds: campgrounds});
        }

    });
});

不幸的是,我无法在网上找到任何好的例子。

我希望索引在点击指向/ campgrounds的链接后加载不同的mongo集合,我想将其更改为/:locations_id。

主页面将分别有3个指向location1,location2和location3的链接。

有没有办法在/:locations_id加载不同的集合(位置1,2或3),具体取决于之前点击的链接?

我的想法是使用req.params.locations_id并且可能在点击的链接上附加一些信息并在if语句中使用它以加载正确的集合。

非常感谢你的帮助,我为极其概念化的问题道歉。

1 个答案:

答案 0 :(得分:0)

嗯,我想你可以耍一招。

//Put every collection in an array
var collections = [
  Campground,
  Collection2,
  Collection3
];

//When user visits: example.com/campgrounds/1
router.get("/campgrounds/:locationId", function(req,res) {
  //Parse the index from the URL
  var locId = parseInt(req.params.locationId);

  //Make sure that we aren't blown up :)
  if(isNaN(locId) || locId > 2) {
    //Default collection's index - which is Campground in this example
    locId = 0;
  }

  //Match the given collection by its index and return it
  collections[locId].find({}, function(err, campgrounds) {
    if(err) {
      console.log(err);
    } else {
      res.render("campgrounds/index", {campgrounds: campgrounds});
    }
  });
});