How to write callback function for getting the collection object in nodejs.Here is java script function i wrote for getting collection object 中的nodejs.Here是我为获取集合对象编写的脚本函数

How to write callback function for getting the collection object in nodejs.Here is java script function i wrote for getting collection object

function get_db_connection(database_name,collection_name){
    var collection;
    MongoClient = require('mongodb').MongoClient;
    // Connect to the db
    MongoClient.connect('mongodb://localhost:27017/'+database_name, function(err, db) {
        if(!err) { 
            collection=db.collection(collection_name);
            console.log(collection);
        } else { 
            console.log(err);
        }  
    });
    return collection;
}

我只是对如何将参数传递给回调感到困惑..如果有人 post 帮助 link 会更好 link..

您不能从异步函数中return,您需要使用回调。

function get_db_connection(database_name, collection_name, callback) {
    var MongoClient = require('mongodb').MongoClient;
    // Connect to the db
    MongoClient.connect('mongodb://localhost:27017/' + database_name, function(err, db) {
        if(err) { 
            return callback(err);
        }
        callback(null, db.collection(collection_name));
    });
}

然后您可以像这样使用它

get_db_connection(database_name, collection_name, function(error, collection) {
    //do something with collection
});