node.js mongodb javascript scoping confusion

前端 未结 1 1587
长发绾君心
长发绾君心 2021-01-26 00:34

I\'m developing a express.js application, without mongoose.

What I\'m trying to do is, to encapsulate calls to mongodb inside a function, pass the function some paramete

相关标签:
1条回答
  • 2021-01-26 01:06

    Since the items are retrieved from MongoDB asynchronously, the function get_data needs to accept a callback that will be used to return the results. I believe you'll also need to explicitly open the database connection.

    function get_data(callback) {
        ...
    
        db.open(function(err, db) {
            if (err) return callback(err);
    
            db.collection('test_collection', function(err, collection) {
                if (err) return callback(err);
                collection.find().toArray(callback);
            });
        });
    }
    
    get_data(function(err, items) {
        // handle error
        console.log(items);
    });
    
    0 讨论(0)
提交回复
热议问题