-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.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
jayesh hathila
  • 279
  • 1
  • 6
  • 14

1 Answers1

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

Community
  • 1
  • 1
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84