最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Error handling under Mongoose save() - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Aug 31, 2013 at 18:31 JahmJahm 6681 gold badge12 silver badges28 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 8

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

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

    });

};

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

发布评论

评论列表(0)

  1. 暂无评论