How can I promisify the MongoDB native Javascript driver using bluebird?

前端 未结 5 589
情书的邮戳
情书的邮戳 2020-11-27 17:41

I\'d like to use the MongoDB native JS driver with bluebird promises. How can I use Promise.promisifyAll() on this library?

5条回答
  •  我在风中等你
    2020-11-27 18:11

    I know this has been answered several times, but I wanted to add in a little more information regarding this topic. Per Bluebird's own documentation, you should use the 'using' for cleaning up connections and prevent memory leaks. Resource Management in Bluebird

    I looked all over the place for how to do this correctly and information was scarce so I thought I'd share what I found after much trial and error. The data I used below (restaurants) came from the MongoDB sample data. You can get that here: MongoDB Import Data

    // Using dotenv for environment / connection information
    require('dotenv').load();
    var Promise = require('bluebird'),
        mongodb = Promise.promisifyAll(require('mongodb'))
        using = Promise.using;
    
    function getConnectionAsync(){
        // process.env.MongoDbUrl stored in my .env file using the require above
        return mongodb.MongoClient.connectAsync(process.env.MongoDbUrl)
            // .disposer is what handles cleaning up the connection
            .disposer(function(connection){
                connection.close();
            });
    }
    
    // The two methods below retrieve the same data and output the same data
    // but the difference is the first one does as much as it can asynchronously
    // while the 2nd one uses the blocking versions of each
    // NOTE: using limitAsync seems to go away to never-never land and never come back!
    
    // Everything is done asynchronously here with promises
    using(
        getConnectionAsync(),
        function(connection) {
            // Because we used promisifyAll(), most (if not all) of the
            // methods in what was promisified now have an Async sibling
            // collection : collectionAsync
            // find : findAsync
            // etc.
            return connection.collectionAsync('restaurants')
                .then(function(collection){
                    return collection.findAsync()
                })
                .then(function(data){
                    return data.limit(10).toArrayAsync();
                });
        }
    // Before this ".then" is called, the using statement will now call the
    // .dispose() that was set up in the getConnectionAsync method
    ).then(
        function(data){
            console.log("end data", data);
        }
    );
    
    // Here, only the connection is asynchronous - the rest are blocking processes
    using(
        getConnectionAsync(),
        function(connection) {
            // Here because I'm not using any of the Async functions, these should
            // all be blocking requests unlike the promisified versions above
            return connection.collection('restaurants').find().limit(10).toArray();
        }
    ).then(
        function(data){
            console.log("end data", data);
        }
    );
    

    I hope this helps someone else out who wanted to do things by the Bluebird book.

提交回复
热议问题