I have been trying to send
a message to the browser when there is an error saving a document
to my MongoDB database
. I'm using Mongoose
as a wrapper to it.
This is my signup.js
var mongoose = require('mongoose');
var models = mongoose.models;
exports.user = function(req, res){
var u = new models.Users(req.body);
u.save(function(err, user) {
if (err) {
console.log(err);
res.send(400, 'Bad Request');
}
res.redirect('/');
});
};
If an err
has been detected, it displays the err
message to the log, but won't send
Bad Request
to the browser.
Am I doing this wrong?
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");
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With