Dynamically pick values from req.body based on database attributes

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Dynamically pick values from req.body based on database attributes



I am building an app usine Node/EJS/Mongo where the user is building a capability survey, and needs to set the desired level for each question. The form that they use to pick the levels has a series of selects that look like:


<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>



When the user then submits this form, I want to update the assessment to load in these expected levels.



The schema for assessments in my mongodb looks like:


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



What I am thinking is I want to loop through all the capabilities, find the entry in req.body that has a name that matches capabilityId, and then update desiredLevel. I just can't see how to make it work. My route code currently looks like:


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









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

wVd N17gv o Y,yO0mLrQhhzvHoZs,C,YTuLbQT5VEre kfg3FYV PNT n5usd
Klhr1BEUuMgzuZeVzpw7Nar

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results