1

I want to perform a find query to MongoDB to check whether a particular entry is in DB or not. But it calls a callback function which is asynchronous. How can I get the result?

In this I am not getting the actual result synchronously.

1
  • Can you post the sample code ? Are you directly using the node.js MongoDB driver ? or you are using anything like Mongoose ? Commented Nov 30, 2011 at 9:16

1 Answer 1

4

If you are using Node.js you ought to do it the asynchronous way.

Example:

db_call(query, function (err, result) {
  if (err) { throw new Error('db_error'); return; }
  console.log(result); // do your stuff here
});
Sign up to request clarification or add additional context in comments.

2 Comments

I am using the same way like: function authenticateUser(msg) { var result = true; db.open(function (error, client) { if (error) throw error; var collection = new mongodb.Collection(client, 'users'); collection.find({'key':msg}).toArray(function(err, docs) { log.info(docs.length); if(docs.length != 1) result = false; }); }); return result; } In this case I am not getting result value when I call this authenticate method.As we do not know when callback will be fired.
right place to post your code would be in the original question and not in comment section. If there is a lot of code you can use gist.github.com.

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.