从这个问题的后续>Stopping response if document isn't found因为它被推荐我使用Promise。从猫鼬承诺返回回应
所以基本的前提是,如果我们无法在数据库中找到id,节点将返回“无法找到ID”消息。
v1.post("/", function(req, res) {
// If the project_id isn't provided, return with an error.
if (!("project_id" in req.body)) {
return res.send("You need to provide Project ID");
}
// Check if the Project ID is in the file.
helper.documentExists(ProjectsData, {project_id: req.body.project_id})
.then(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);
})
};
});
});
而且helper.documentExists
module.exports = {
documentExists: function(collection, query) {
return collection.count(query).exec();
},
};
但脚本将继续在此之后运行并打印“未找到所需的数据”。
Output:
required data not found
1
我正在使用原生ES6承诺。
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
编辑:包括整个获取路线。 (以后会解决这些抛ERR)
'console.log(“required data not found”); ''''''''''''会运行任何计数,因为它超出了承诺然后回调 – Iceman
哦,我认为Promise会在它低于它的任何东西之前运行。否则阻止? – DragoonHP
是的,你应该。看到我的答案有点洞察力! – Iceman