如果找不到文档,则停止响应 [英] Stopping response if document isn't found

查看:33
本文介绍了如果找不到文档,则停止响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本检查数据库中是否存在ID.如果没有,应该在那儿停止逻辑.

My script checks if an id exists inside the database. If it doesn't, it's supposed to stop the logic right there and then.

但是当前发生的情况是返回请发送所有必需的详细信息",而不是返回所提供的项目ID在我们的数据库中不存在.".(可能是因为第一次返回使我们退出了该功能)

But what happens currently is instead of returning the "The provided Project Id does not exist in our database.", it returns "Please send all the required details.". (Probably because the first return takes us out of the function)

var projectExists = function(pId, callback) {
    ProjectsData.count( {project_id: pId}, function(err, doc) {

        if (err) {
            throw err;
        }
        callback(doc);
    });
};

// Create a new Game ID.
v1.post("/", function(req, res, next) {

    if ( !("project_id" in req.body) ) {
        return res.send("You need to provide Project ID");
    }

    // Check if the Project ID is in the file.
    // Problematic bit
    projectExists( req.body.project_id, function(c) {
        if ( c == 0 ) {
            return res.send("The provided Project Id does not exist in our database.");
        }
    });

    var gameDataObj = req.body;

    GameData.addGameId(gameDataObj, function (err, doc) {
        if (err) {
            if (err.name == "ValidationError") {
                return res.send("Please send all the required details.");
            }
            throw err;
        };

        res.json(doc);
    })
});

我做错了什么?有更好的方法吗?

What am I doing wrong? Is there any better way of doing this?

还有一个后续问题;在当前迭代中,如果id错误,也会出现此错误:

And a follow up question; in the current iteration, if the id is wrong there is also this error:

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header (G:\node\vnlytics\node_modules\express\lib\response.js:719:10)
    at ServerResponse.send (G:\node\vnlytics\node_modules\express\lib\response.js:164:12)
    at G:\node\vnlytics\controllers\v1\game.data.js:35:17
    at G:\node\vnlytics\controllers\v1\game.data.js:20:9
    at Query.<anonymous> (G:\node\vnlytics\node_modules\mongoose\lib\model.js:3331:16)
    at G:\node\vnlytics\node_modules\kareem\index.js:259:21
    at G:\node\vnlytics\node_modules\kareem\index.js:127:16
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickCallback (node.js:349:13)

可能是因为我们正在发送两个响应,但是奇怪的是检查res.headersSent直到最后一刻返回false.

It's probably because we are sending two response but what's weird is that checking res.headersSent until the last moment returns false.

推荐答案

正如我在评论中所说,您需要正确地对异步操作进行排序,以便在知道上一个操作的结果之前,不要启动下一个操作并已经处理了.您可以这样做:

As I said in my comment, you need to properly sequence your async operations so you don't start the next one until you know the result of the previous one and have processed that. You can do that like this:

// Create a new Game ID.
v1.post("/", function(req, res, next) {

    if ( !("project_id" in req.body) ) {
        return res.send("You need to provide Project ID");
    }

    // Check if the Project ID is in the file.
    // Problematic bit
    projectExists( req.body.project_id, function(c) {
        if ( c == 0 ) {
            return res.send("The provided Project Id does not exist in our database.");
        } else {
            var gameDataObj = req.body;

            GameData.addGameId(gameDataObj, function (err, doc) {
                if (err) {
                    if (err.name == "ValidationError") {
                        return res.send("Please send all the required details.");
                    }
                    throw err;
                };

                res.json(doc);
            })
        }
    });

});

P.S.您应使用正确的错误处理方法替换 throw err .您实际上需要在此处发送错误响应. throw 除了在从未发送响应时停止处理之外,不会做任何有用的事情.

P.S. You should replace the throw err with proper error handling. You need to actually send an error response here. The throw won't do anything useful other than stop processing when a response has never been sent.

这篇关于如果找不到文档,则停止响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆