简体   繁体   中英

mongodb find() return empty result in node.js

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM