Reputation: 668
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?
Upvotes: 8
Views: 24648
Reputation: 89
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");
});
};
Upvotes: 4
Reputation: 31
Alternatively, you could return res.redirect('/');
so code execution would stop.
Upvotes: 3
Reputation: 617
add an else
before res.redirect('/');
. Its probably sending a 400 and then redirecting to /
Upvotes: 8