根据数据库属性动态地从req.body中选取值



我正在构建一个应用程序usine 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);
}
});
});
});

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

req.body[variable];

最新更新