0

I am attempting to break out of a function based on an expression, however am having trouble with the scoping. Here is a snippet of the code:

function createService(dict, res) {
    // Ensure no duplicate
    var serviceExists = Service.find({name: dict['name']}).count().exec(function(err, doc) {
        return (doc !== 0);
    });

    console.log(serviceExists);

    if(serviceExists){
        res.send(500, "Duplicate document. Try updating existing entry or chooseing a different name");
        return;
    }

    //Insert the document
    service = new Service(dict);
    service.save(function(err) {
        if(!err) {
            res.send("Service saved");
        }
    });
}

The output of the console.log():

{ emitted: {},
  _events: { err: [Function], complete: [Function] } }

The end goal here is that the code will not reach the "Insert the document" portion if doc !== 0. Please let me know the correct way of doing this (Maybe using exceptions? That is the only idea I have left). Thanks

tgrosinger
  • 2,463
  • 2
  • 30
  • 38
  • I got this result when looking for how to pass extra values to a call back. I found out how to do that and posted it here: http://stackoverflow.com/a/28120741/1695680 – ThorSummoner Jan 24 '15 at 00:05

1 Answers1

1

Service.find is asynchronous. the callback in exec doesn't execute immediately. This causes problem 1. (If Service....exec(...) returned a value, your console.log would have already excuted, before the callback.)

Problem 2 is also pretty common. return in exec() doesn't return a value you can assign to a variable. (exec() does not return the return value of your anonymous function.)

Here is a fix for your code:

function createService(dict, res) {
    // Ensure no duplicate
    Service.findOne({name: dict['name']}).count().exec(function(err, doc) {
        var serviceExists = (doc !== 0);
        console.log(serviceExists);
        if(serviceExists){
            res.send(500, "Duplicate document. Try updating existing entry or chooseing a different name");
            return;
        }

        //Insert the document
        service = new Service(dict);
        service.save(function(err) {
            if(!err) {
                res.send("Service saved");
            }
        });
    });
}

I also changed find to findOne, otherwise you'll get an array instead of a doc.

rdrey
  • 9,379
  • 4
  • 40
  • 52