Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling under Mongoose save()

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?

like image 710
Jahm Avatar asked Aug 31 '13 18:08

Jahm


3 Answers

add an else before res.redirect('/'); . Its probably sending a 400 and then redirecting to /

like image 195
Rana Deep Avatar answered Oct 12 '22 09:10

Rana Deep


Alternatively, you could return res.redirect('/'); so code execution would stop.

like image 37
Bruno Fabbri Avatar answered Oct 12 '22 10:10

Bruno Fabbri


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");

    });

};

like image 33
Mega Alpha Avatar answered Oct 12 '22 10:10

Mega Alpha