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

1
  • 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: stackoverflow.com/a/28120741/1695680 Commented Jan 24, 2015 at 0:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you rdey. Don't know why it didn't occur to me that this was async.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.