I am new to node.js and I am just wondering what you think about this code. For me, it seems there are too many conditions in the code. Is there any way to refactor it?
var removeQuestions = function(questions) {
if (questions.length < 1)
return;
var group_name = questions[0].group;
var metagroup_name = questions[0].metagroup;
// update count in groups
QuestionGroupModel.find({group: group_name}).exec(function(err, groups) {
if(!err) {
groups[0].cnt = groups[0].cnt - questions.length;
if(groups[0].cnt > 0) {
groups[0].save(function(err2) {
if(err2)
console.info('error while updating group info');
});
} else {
QuestionGroupModel.find({group: groups[0].group}).remove(function(err3) {
if(!err3) {
console.info('groups %s was deleted', groups[0].group);
} else {
console.info('error while deleting group');
}
});
}
} else {
console.info('error while lookup group info');
};
});
// delete questions
for (var i = 0; i < questions.length; i++) {
QuestionModel.remove({ _id: questions[i]._id }, function(err) {
if(!err) {
log.info("question removed");
}
});
}
};
1 Answer 1
Almost all of your conditions are error handling, so there's not a lot to clean up. For clarity's sake, I would make your initial error handler a guard condition, which makes it much more obvious what's going on. I would then break out all your inner functions into labeled functions, which makes it clear what you're trying to achieve:
QuestionGroupModel.find({group: group_name}).exec(function(err, groups) {
if (err) {
console.info("Error while lookup group info", err);
return;
}
var deleteGroup = function(group) {
QuestionGroupModel.find({group: groups[0].group}).remove(function(err) {
console.info.apply(null, (err) ? ['error while deleting group', err] : ['groups %s was deleted', group]);
});
};
var saveGroup = function(group) {
group.save(function(err2) {
if(err2)
console.info('error while updating group info');
});
};
groups[0].cnt = groups[0].cnt - questions.length;
if (groups[0].cnt > 0) {
saveGroup(groups[0]); // That you have two different arguments for similar operations is a code smell.
} else {
deleteGroup(groups[0].group);
}
});
I don't have a clear picture of your QuestionGroupModel, but that they take different arguments for similar operations shows that the model itself has problems, and may require refactoring.