node.js - Handling saves and redirects asynchronously in node js and mongoose -
i new node.js , trying understand asynchronous nature of how stuff works. ok simple form submission.the model looks below:-
var mongoose=require('mongoose'); var schema=mongoose.schema; var postschema=new schema({ title:{type:string,required:true}, post:string, }); var postmodel=mongoose.model('blogpost',postschema); module.exports=postmodel;
and route handler below:-
app.post("/submitpost",function(req,res){ var title=req.body.title; var post=req.body.post; var thepost=new postmodel({title:title,post:post}); thepost.save(function(err,data){ if(err)throw err; console.log(data); }) console.log("title "+title); console.log("post "+post); res.send("saved"); });
now suppose validation fails during "thepost.save(callback)" , want show error page rather "saved" . how that?
simply move rendering of response callback:
app.post("/submitpost",function(req,res){ var title=req.body.title; var post=req.body.post; var thepost=new postmodel({title:title,post:post}); thepost.save(function(err,data){ if(err) { res.render('errorpage'); } else { console.log(data); console.log("title "+title); console.log("post "+post); res.send("saved"); } }) });
Comments
Post a Comment