-1
function addToServer(myid) {
    console.log("jayesh"+db.server.find({id:myid})+"\n");
    return db.server.find({id:myid});
};
addToServer(myid,function(resp) {
    console.log("something");
    if(resp.count()>0)
        console.log("present");
    else
        console.log("Nope");
});

I want to know whether document with id = myid is present in server collection. I guess there is some issue with callback but being a novice don't have much a knowledge about it. Please help me out.Thanks

P.S For function I am getting output saying "jayesh[object Object] " and nothing is printing for callback method.

2
  • 1
    Well, that db.find call is async, so you have to wait for an answer (callback) -- and go from there. Commented Jan 13, 2014 at 19:51
  • Where is your callback being executed in addToServer()? Commented Jan 13, 2014 at 19:52

1 Answer 1

2

The problem is you trying to write synchronous code inside an asynchronous environment.

You need to pass callbacks:

function addToServer(myid, cb) {
    db.server.find({id:myid},cb);
};

addToServer(myid,function(err, resp) {
    if(err) {
      console.log("err");
    } else if(resp.count()>0) {
      console.log("present");
    } else {
      console.log("Nope");
    }
});

In async programming you cannot throw and cannot return you use callbacks instead!

These callbacks are conventionally invoked with an error object (alternative to throw) as the first argument and all other arguments with the returned data (alternative to return).

Reading Material on Async Programming Practices

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

Comments

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.