2016-12-02 3 views
0

私は助けが必要です!私はこのコードを持っています:ノードとマングース - リンクをクリックした後に正しいコレクションを読み込む

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

    }); 
}); 

残念ながら私は良い例をオンラインで見つけることができませんでした。

/:locations_idに変更したい/ campgroundsにつながるリンクをクリックした後、別のmongoコレクションを読み込むためのインデックスが必要でした。

メインページにはそれぞれlocation1、location2、location3へのリンクが3つあります。

以前にクリックしたリンクに応じて、/:locations_idに別のコレクション(場所1、場所2、場所3)を読み込む方法はありますか?

私の考えは、req.params.locations_idを使用し、クリックされたリンクに情報を追加し、正しいコレクションを読み込むためにifステートメントで使用することでした。

ご協力いただきありがとうございます。非常に概念的な質問をお詫び申し上げます。

答えて

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}); 
    } 
    }); 
}); 
関連する問題