0

I have the following problem with mongodb-native. I have a function whose purpose is to return some element from db.

function get(){
  db.collection('test').findOne({...},{...},function(err, doc){
     // my doc is here
  });
  // but here my doc is undefined
  // so I can not return it

  return doc;
}

So due to asynchroneous nature of node, I can not get my doc back. So how can I make it synchroneous (or is there any other way)?

I need for my single page app. So when my client does some action, ajax request is sent which is handled by get function. This function has to send back JSON.

Stennie
  • 63,885
  • 14
  • 149
  • 175
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753

1 Answers1

1

The answer is to have your code work asynchroneous, that is the whole concept of JavaScript.

Thus if you have something like this in your synchroneous program:

function get() {
  db.collection('test').findOne({...},{...},function(err,doc) {
  });
  return doc;
}

var doc = get();
console.log(doc);

You can refactor it into:

function printToConsole(err, doc) {
    console.log(doc);
}
function get(callback) {
    db.collection('test').findOne({...},{...},callback);
}
get(printToConsole);

It is not a unique solution, there are other workflows. Some like promises will make your code flatter.

But my personal suggestion, is to initially learn how to code asynchroneous code without supporting libraries. Initially it feels like a pain, just give it some time and you will start enjoying the idea.

alandarev
  • 8,349
  • 2
  • 34
  • 43
  • I am aware of asynchroneus concept of JS from client side JS. Right now I just need to understand the concepts for the server-side to solve problems that I was previously solving with synchroneous languages. I edited a question to make clear why exactly do I need it. – Salvador Dali Jul 04 '14 at 08:30
  • Server-side code shares same concept. Your demand of JavaScript to become synchroneous, is like using Java as functional language. There is no mongodb `find` sync version of a function. – alandarev Jul 04 '14 at 08:44