0

In my node application i am using mongodb for datastorage by using Mongoose.In that the following is my code:

 var client = new OAuthClient({"name":"default"});
        client.user = req.user;
        client.username = req.body.username;
        console.log("b4 save");
        client.save();

        OAuthClient.find({username:req.body.username}).exec(function(err, clients) {                
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            console.log("clientssssssss=" + util.inspect(clients));
            res.jsonp(clients);
        }
      });

But

console.log("clientssssssss=" + util.inspect(clients)); Is returning empty array[].

while i execute the command in my ROBOMONGO the result is returned. suppose consider my query is like this OAuthClient.find({username:'user4'}) the result is coming, but with the above code its returning empty array. Help me to solve this. Thanks in advance..

2
  • 1
    Please check, is that query the right collection? Commented Jul 23, 2014 at 7:46
  • @ Muhammad Ali Yes is that in correct collection Commented Jul 23, 2014 at 7:48

1 Answer 1

1

Your problem is callbacks as shown here:

client.save();   // <-- not waiting for callback

    OAuthClient.find({username:req.body.username}).exec(function(err, clients) {                
    if (err) {

You need to wait for the callback as .save() is not guaranteed of completion. Do instead: client.save(function(err,client) {

    OAuthClient.find({username:req.body.username}).exec(function(err, clients) {                
        if (err) {

        }

        //body of work
    });

});

Where everything is inside the callback from .save()

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

2 Comments

@ Neil Lunn r u saying that inside .save function i have to do the find query?? Also can you please align the code correctly what you have posted..
@Subburaj. Essentially yes. What I am really saying is that the line following .save() does not wait for .save() to complete. This is asynchronous and only inside the "callback" argument of .save() do you know this has completed and the document you are trying to retrieve is actually there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.