繁体   English   中英

Nodejs + mongodb中REST API的自定义URL

[英]Custom URL for REST API in Nodejs + mongodb

所以我在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'
}

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

由于使用的是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对象,包含请求的所有查询参数,因此请求类似于

/个人资料?ID = 1234&域=名称

会导致像

{ 
  id: '1234',
  fields: 'name'
}

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

我同意丹尼尔(Daniel)的看法,他没有回答您的完整问题。 这是一个示例,该如何做您要寻找的东西,您必须自己进行猫鼬查询。

 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{
        }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM