User Schema:
var userSchema = new mongoose.Schema({
user: String,
data: [{}]
});
In the schema above, I am adding question and option(MCQ) user marked inside the data array. I can add new answers successfully but can't update already answered question with different options.
Server side code:
let user = await User.findOne({ user: req.body.user });
let checkUser = user.data.filter(res => res.quesId == req.body.id);
if (checkUser.length) {
// Logic for updating
} else {
await user.data.push({
quesId: req.body.id,
option: req.body.opt
});
user.save();
}
So what I want to do is that if the user answered the same question(determined by req.body.id) with different option(req.body.opt), it should be updated in the already existing record.
To update an object inside an array, you need to remove the original object then create a new one with the new data included.
Example:
// Define required variables
let user = await User.findOne({ user: req.body.user });
let data = user.data;
let checkUser = data.filter(res => res.quesId == req.body.id);
// If the question already exists
if (checkUser.length > 0) {
// Loop through the questions that already exist
checkUser.forEach(question => {
// Remove the question from the users data
data.splice(data.indexOf(question), 1);
// Append the new data onto the array
data.push({
quesId: req.body.id,
option: req.body.opt
});
// Save the new data
user.data = data;
user.save();
});
} else {
// If the question doesn't already exist, create it
(user.data).push({
quesId: req.body.id,
option: req.body.opt
});
// Save the changed data
user.save();
}