I'm very new to Node/Express, and trying to implement this block that updates a company's information. I have a number of console.log
statements that are tracking the variables throughout the block, and everything seems to be working perfectly fine until the last saving line. What exactly could I be doing wrong?
// Edit company metric information
editMetrics: function(link, form, cb) {
Companies.findOne({ permalink: link }, function (err, company) {
if (err) return done(err);
// Iterate through form fields
for(var field in form) {
console.log(field); // Looks great
if(typeof(company.operational[field]) !== 'undefined') {
company.operational[field].unshift({
timestamp: new Date(),
value: form[field]
});
}
if(typeof(company.user_metrics[field]) !== 'undefined') {
company.user_metrics[field].unshift({
timestamp: new Date(),
value: form[field]
});
}
if(typeof(company.economics[field]) !== 'undefined') {
company.economics[field].unshift({
timestamp: new Date(),
value: form[field]
});
}
}
console.log(company); // Looks great
// Save & redirect to updated profile
company.save(cb()); // For some reason this isn't saving
});
},
Callback:
CompanyModel.editMetrics(link, req.body, cb = function(error, result) {
res.redirect('/portfolio/' + link);
});
The problem is the last line:
company.save(cb());
should be:
company.save(cb);
Basically you are executing the callback and passing the result to the save function, when you need to be passing the function pointer to the save function.
Also make sure your callback signature matches the node convention of function(error, result)
so that you get the result value you are expecting.