DragoonHP DragoonHP - 4 months ago 22
Node.js Question

Returning response from Mongoose promise

Followup from this question > Stopping response if document isn't found since it was recommended I use Promise.

So basic premise, I want node to return "Can't find ID" message if we can't find the id in our database.

ProjectsData.count( {project_id: req.body.project_id} )

.then(function(c) {
if ( c == 0 ) {
console.log("1");
return res.send("The provided Project Id does not exist in our database.");
console.log("2");
}
});

//some other logic
console.log("required data not found");


But the script continues to run after this and prints the "required data not found".

Output:
required data not found
1


I am using native ES6 Promises.

var mongoose = require("mongoose");
mongoose.Promise = global.Promise;

Answer
#######POINT 1#########
ProjectsData.count( {project_id: req.body.project_id} )

    .then(function(c) {
        #######POINT 3#########
        if ( c == 0 ) {
            console.log("1");
            return res.send("The provided Project Id does not exist in our database.");
            console.log("2");
        }
    });
#######POINT 2#########
//some other logic
console.log("required data not found");

Following async workflow: after POINT 1, there is no guarantee POINT 2 OR 3 will run first. Either can, but mostly 2 because 2 because 3 is a time consuming place.

So simply put POINT 2 code in the else{} of the if at POINT 3 (as you rightly guessed in the comments)