根据数据库属性从req.body动态选择值

时间:2018-07-27 10:04:50

标签: javascript node.js express ejs

我正在使用Node / EJS / Mongo构建一个应用程序,用户正在其中构建功能调查,并且需要为每个问题设置所需的级别。他们用来选择关卡的形式具有一系列选择,如下所示:

<select class="form-control col-sm-4" id="<%=capability.capabilityId%>" name="<%=capability.capabilityId%>">
   <option value=1>Developing</option>
   <option value=2>Intermediate</option>
   <option value=3>Advanced</option>
   <option value=4>Role Model</option>
</select>

当用户随后提交此表单时,我想更新评估以加载这些预期水平。

我的mongodb中的评估模式如下:

var assessmentSchema = new mongoose.Schema ({
  title: String,
  startDate: Date,
  endDate: Date,
  behaviours: [{
    behaviourName: String,
    behaviourId: String,
    order: Number,
    capabilities: [{
      orderCap: Number,
      capabilityId: String,
      capabilityName: String,
      capabilityDesc: String,
      developing: String,
      intermediate: String,
      advanced: String,
      roleModel: String,
      expectedLevel: Number,
      motivation1: String,
      motivation2: String,
      motivation3: String,
      motivation4: String,
      motivation5: String
    }]   //capabilities object
  }],
  targetEmployees:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Users"
  }]  //behaviours object
});

我正在想遍历所有功能,在req.body中找到名称与capabilityId相匹配的条目,然后更新desiredLevel。我只是看不到如何使其工作。我的路线代码当前如下所示:

router.put(':id/levels', function(req, res) {
  Assessment.findById(req.params.id, function(err, foundAssessment) {
    foundAssessment.behaviours.forEach(function(b) {
      b.capabilities.forEach(function(c) {
        c.expectedLevel = req.body.SOMETHINGHERE
      });
    });

    foundAssessment.save(function(err) {
      if (err) {
        console.log(err);
        req.flash("error", err.message);
        res.redirect("back");
      } else {
        // Send json back to xhr request
        res.json(foundAssessment);
      }
    });
  });
});

1 个答案:

答案 0 :(得分:1)

您可以读取请求主体动态属性,如下所示:

req.body[variable];