使用可选的猫鼬模型 属性 作为 URL 参数

Using optional mongoose model property as URL param

我正在使用模型的 属性 作为 URL 参数,就像这样 '/parent/:arg1' 控制器是这样处理的

exports.parent = function (req, res) {
  if (typeof(User.profile.property) == undefined) {
    console.log("User does not have property");
  }
  unirest('api.example.com/endpoint/' + User.profile.property)`

但是表示 returns connect 500 typeerror 页面说它无法准备好 属性 'Property' 未定义(这是我所期望的)但是我没有从 typeOf 检查中得到输出我的最终目标是重定向到用户配置文件页面以更新系统。

错误告诉您 User.profile 未定义。抛出错误是因为 User.profile.property 试图访问 undefined 的 属性。您可以将条件检查更新为:

exports.parent = function(req, res) {
  if (User.profile) {
    if (User.profile.property === undefined) {
      console.log("User.profile does not have property");
    } else {
      unirest('api.example.com/endpoint/' + User.profile.property);
    }
  } else {
    console.log("User does not have profile");
  }
}