带有MongoDB的Backbone.js将req.params传递给导出函数

时间:2013-10-21 20:03:05

标签: mongodb backbone.js express parameter-passing params

我正在尝试向express.js,backbone.js应用程序中的mongodb查找发送请求参数到'exports'方法。我很难过 时间让参数传递给mongodb和'#'。

破坏是将参数传递到导出的mongodb函数中。

以下是数据流:

首先,请求成功路由到“即将发布”的功能:

    "upcoming/uni/:uni" : "upcoming",

它没有问题地流向“即将发生的”功能。

    upcoming: function(uni) {
    console.log("uni: "+uni);
    pag.reset();
    console.log("Hit upcoming list target");
    setCollectionType('upcoming');
        var upcomingCourses = buildCollection();

    // ------------------------------------------------------------------------
    // here is the problem how do I pass the parameter value through the fetch?
    // Although it may also have to do with '#' please read on.
    // ------------------------------------------------------------------------
        upcomingCourses.fetch({success: function(){
            $("#content").html(new ListView({model: upcomingCourses, page: 1}).el);
         }});
    this.headerView.selectMenuItem('home-menu');
},

mongo方法的路由是:

app.get('/upcoming/uni/:uni', mongomod.findUpcoming);

因此从mongodb js文件导出以下方法并且执行可靠。然而,req.params没有通过。 散布在代码中我描述了它的'运行时行为:

exports.findUpcoming = function(req, res) {
    console.log("university", req.params.uni); // This consistently is unpopulated
    var uni = req.params.uni;
    console.log("Size: "+req.params.length); // This will always be 0
    for (var i=0; i < req.params.length; i++) {
        console.log("Parameters: "+req.params[i]);
    }

    db.collection('upcoming', function(err, collection) {

    if (typeof uni === 'undefined') {
        console.log("The value is undefined");
        uni = "Princeton University"; // here we add a string to test it it will work.
    }

    collection.find({university:uni}).toArray(function(err, items) {
        if (err) {
            console.log("Error: "+err);
        } else {
            console.log("No Error");
            console.log("Count: "+items.length);
            console.log(items[0]['university']);
            res.send(items);
        }
     });
  });
};

关于其他重要说明:

在工作的运行时环境中,url将是:

http://localhost:3000/#upcoming/uni/Exploratorium

这个失败了,但是下面的URL可以通过这些函数传递params,但它会将JSON返回到屏幕而不是 渲染版本:

http://localhost:3000/upcoming/uni/Exploratorium

问题可能是对#和模板的理解不足。如果您看到错误启示,请非常感谢。

2 个答案:

答案 0 :(得分:1)

#传递给服务器后没有任何内容。请参阅How to get hash in a server side language?https://stackoverflow.com/a/318581/711902

答案 1 :(得分:0)

我找到了将参数从客户端传递到服务器端的问题的解决方案。通过更改集合的url,参数将传递到服务器端:

upcomingCourses.url = "/upcoming/uni/"+uni; // <-- here's the ticket where uni is param
    upcomingCourses.fetch({success: function(){
        $("#content").html(new ListView({model: upcomingCourses, page: 1}).el);
 }});

这可以更优雅,但它是一种将参数传递给服务器的方法。

由于