Handling saves and redirects asynchronously in node js and mongoose
I am new to node.js and am just trying to understand the asynchronous
nature of how this stuff works. Ok this is a very simple form
submission.The model looks like the 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 then the route handler is as 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 is "+title);
console.log("post is "+post);
res.send("saved");
});
Now suppose the validation fails during "thepost.save(callback)" , i would
want to show an error page rather than "saved" . How would i do that?
No comments:
Post a Comment