I have the following code to insert data into DB – this code has to be executed in a sequential order
Router JS
module.exports = function(app) {
app.get('/registerUser', function(req, res ) {
objuser.userName = 'testuser';
objuser.password = 'password';
objuser.status = true;
registerUser (objuser ); //calls Business.js
res.OK();
res.end ();
});
}
Business.js
var registerUser = function (objuser )
{
userDB.registerUser (objuser ) ; //calls db.js
};
db.js
exports.registerUser = function (objUser )
{
var User = db.model(strCollectionName, UserSchema );
var objSchema = new User(objUser);
objSchema.save(function (err)
{
if (err)
console.error (err);
else
console.log ("registerUser : Data insertion success.");
});
}
In the db.js Im getting error from Mongo if I try to insert duplicate value. I wan to pass the error message to HTML page to display the same. What should I do? I tried
throw Error (err)
But it breaks the server.
Assuming you are using expressjs, I’d make use of the
nextcallback. like so:If you don’t want to make your Business.js call async then you will obviously change this code to a
try...catchflow. Node.js apps are happier using async calls though, so a common convention in nodejs apps is to expose a callback using the(err, result)parameters. So yourdb.jscall would be :By now you probably notice that your
Business.jscall would just be a mediator between your route and your db code…whether you need it or not is up to you.HTH,
Mike