【问题标题】:Custom URL for REST API in Nodejs + mongodbNodejs + mongodb 中 REST API 的自定义 URL
【发布时间】:2015-11-07 14:19:33
【问题描述】:

所以我在 nodejs api 中有以下猫鼬模式:

var profileschema = new mongoose.Schema({
    name:           { type: String },
    surname:        { type: String },
    id:             { type: String }
});

还有以下路线:

 var profile = express.Router();

 profile.route('/profile')
      .get(profilecrtl.findAllProfile)
      .post(profilecrtl.addProfile); 

我可以制作其他路线,例如 /profile/:id,它们可以完美运行。

但我想根据用户在同一方法上询问和想要的参数生成自定义 URL,而不必对每种情况进行编码。例如:

  • /profile?id=1234 应该给我关于 id=1234 个人资料的完整信息

{ 
  id: '1234',
  name: 'john'
  surname: 'wicked'
}

  • /profile?id=1234&name=john 应该给我和以前一样的完整个人资料

{ 
  id: '1234',
  name: 'john'
  surname: 'wicked'
}

  • /profile?id=1234&fields=name 应该只给我 id=1234 配置文件的名称

{ 
  name: 'john'
}

相同情况中是否有任何稳健的方法可以做到这一点,以便在未来发生任何变化时轻松扩展?

【问题讨论】:

    标签: javascript node.js rest express


    【解决方案1】:

    由于您使用的是 Express,因此您应该使用 req.query 来获取带有请求参数的对象。

    profile.get('/profile', function (req, res) {
        var query = req.query;
        //Depending on what the query contains, find stuff in your DB with mongoose!
    });
    

    req.query 是一个 JSON 对象,包含请求的所有查询参数,所以像

    这样的请求

    /profile?id=1234&fields=name

    会产生像

    这样的 JSON 对象
    { 
      id: '1234',
      fields: 'name'
    }
    

    您可以从中创建数据库查询。

    【讨论】:

    • 感谢您的回答,我已经添加了一些示例。我了解 req.query 的工作原理,但考虑到 get 请求可能非常动态,我想尽可能笼统地做。
    【解决方案2】:

    我同意 Daniel 的观点,但他没有回答您的全部问题。 这是一个示例,如何执行您要查找的内容,您必须自己执行 mongoose 查询。

     profile.get('/profile', function (req, res) {
        var query = req.query;
          if(query.id&& !query.field)
           {
              //the user is asking for the full profile
           }else if(query.field)
           {
              switch(query.field)
              {
                case "name":
                 //the user is asking for the field name
                break;
              }
           }else{
            }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2014-05-06
      • 2019-04-27
      • 2018-10-12
      相关资源
      最近更新 更多