What is the right way to make a synchronous MongoDB query in Node.js?

后端 未结 3 1141
礼貌的吻别
礼貌的吻别 2020-11-29 01:50

I\'m using the Node.JS driver for MongoDB, and I\'d like to perform a synchronous query, like such:

function getAThing()
{
    var db = new mongo.Db(\"mydata         


        
3条回答
  •  再見小時候
    2020-11-29 02:32

    While it's not strictly synchronous, a pattern I've repeatedly adopted and found very useful is to use co and promisify yield on asynchronous functions. For mongo, you could rewrite the above:

    var query = co( function* () {
    
        var db = new mongo.Db("mydatabase", server, {});
        db = promisify.object( db );
        db = yield db.open();
    
        yield db.authenticate("myuser", "mypassword");
    
        var collection = yield db.collection("Things");
        return yield collection.findOne( { name : "bob"} );
    
    });
    
    query.then( result => {
    
    } ).catch( err => {
    
    } );
    

    This means:

    1. You can write "synchronous"-like code with any asynchronous library
    2. Errors are thrown from the callbacks, meaning you don't need the success check
    3. You can pass the result as a promise to any other piece of code

提交回复
热议问题