Error handling under Mongoose save()
add an else
before res.redirect('/');
. Its probably sending a 400 and then redirecting to /
Alternatively, you could return res.redirect('/');
so code execution would stop.
Using Promises are better and It Fix my issue for me
I had a similar issue and fix it by using the Promise returned by the u.save() in your example.
var mongoose = require("mongoose");
var models = mongoose.models;
exports.user = function (req, res) {
var u = new models.Users(req.body);
u.save()
.then((user) => {
// If everything goes as planed
//use the retured user document for something
res.redirect("/");
})
.catch((error) => {
//When there are errors We handle them here
console.log(err);
res.send(400, "Bad Request");
});
};