简体   繁体   中英

How to return from find in nodejs,mongoose mongodb collection

While find() element in mongodb collection, using mongoose, the console.log doesn't executed in the Test.js

In the Test.js , the console.log doesn't print the data from the MongoDb collection

var model =  require('./model');
model.findbyTag('java',function (data)
{
    console.log(data)
});

The Model.js has the following entry

exports.findbyTag = function(tag,out)
{
    var condtion = {"tag" : tag}
     Tag.find(condtion,function(err,out){
          //  console.log(out);
             if (err) console.log('Error returning Tag!');
            else {
               return out;
            }
        });
}

When i uncomment the console.log file in the Model.js , it's log the data matched in the find query,

The callback in test.js file doesn't executed, did i successfully returning data from the Model.js , what wrong i'm doing ?

In Model.js findbyTag method is returning function object instead of executing callback function . Also, queried document need to be passed as an argument to callback function. It can be modified like:

exports.findbyTag = function(tag,out)
{
    var condtion = {"tag" : tag}
     Tag.find(condtion,function(err,doc){
          //  console.log(doc);
             if (err) console.log('Error returning Tag!');
            else {
               out(doc);
            }
        });
}

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