Dirk Dirk - 22 days ago 11
Node.js Question

Respond inside callback does nothing in node Express

I'm using node Express for my backend application.
I wrote a method that gets some input from express request object. The method does some checks and write messages to the respond object via res.write(...). At the end of all checks I call res.end(); So far so good.
Some of my checks require a mongodb access therefore I have to work with callbacks. Here's some code:

app.post("/addUser", function (req, res) {
expdb.unique({ "email": req.body.email }, function (isUnique) {
if (!isUnique) {
res.write("email error");
}
})
expdb.unique({ "_id": req.body.user }, function (isUnique) {
if (!isUnique) {
res.write("user error");
}
})
/* -- below here everything works fine -- */
if (req.body.user.length < 3 || req.body.user.length > 20) {
res.write("username to short ...or to long");
}
/* -- ... more working code -- */
res.end();
});


The first two responds are completely ignored.
I´m pretty sure some funky callback magic is happening here but I can't figure out how to do it right.
I tried something like below to be sure the callback knows the respond object but it also failed:

expdb.unique({"_id": req.body.user}, function(result, respond) {
if(!result) {
respond.write("user error")
}
}, res)


May somebody help me with this.

thanks
-Dirk

Answer

As is mentioned in the comments, the following should work

var theEnd = function(response){
   if (req.body.user.length < 3 || req.body.user.length > 20) {
     res.write("username to short ...or to long");
   }
   /* -- ... more working code -- */
   res.end();
};

app.post("/addUser", function (req, res) {
  expdb.unique({ "email": req.body.email }, function (isUnique) {
    if (!isUnique) {
        res.write("email error");
    }
    theEnd(res);
  })
  expdb.unique({ "_id": req.body.user }, function (isUnique) {
    if (!isUnique) {
        res.write("user error");
    }
    theEnd(res);
  })