2016-08-26 21 views
6

現在ノード4.3.2とmongo 2.6を使用しています。私は全体のコレクションを取得しようとしています(コレクションに現在3つのドキュメントがあります)。私はこのコードを使用すると問題にぶつかります。cursor.toArray()は配列の代わりに約束を返します

function checkUpdateTime(last_updated){ 
    var collection = db.collection(last_updated); 
    collection.insert({a:1}); 
    updateTimes = collection.find({a:1}).toArray(); 
} 
var updateTimes = []; 
checkUpdateTime('last_updated'); 
console.log(updateTimes); 

このコードがtunの場合、updateTimesは約束であり、私が望んでいた配列ではありません。目標は、配列を編集して後でコレクションに挿入することです。挿入ステートメントは機能しますが、ドキュメントの取得は単に私が期待していた方法では動作しません。私はこのコードのかなりのバージョンを試しましたが、サイコロはありませんでした。

私はそれは約束が返されている理由を不思議に私に帰着すると思いますか?そうでない場合は、発信者

への約束を返すことで、発信者

  • によって渡されるコールバックを通じ

  • 答えて

    9

    MongoDBのドライバは、非同期操作を処理するための2つのオプションを提供していますあなたの場合のようにコールバックを渡すと、約束が返されます。

    だから、ここで選択をする必要があります。あなたが選択できない1つの選択肢は、"このコードを同期させる"です。

    私は約束を好む:

    function checkUpdateTime(last_updated){ 
        var collection = db.collection(last_updated); 
        return collection.insert({ a : 1 }) // also async 
            .then(function() { 
            return collection.find({ a : 1 }).toArray(); 
            }); 
    } 
    checkUpdateTime('last_updated').then(function(updateTimes) { 
        console.log(updateTimes); 
    }); 
    

    あなたはいつももう少し派手に行くとPromise.coroutineのようなものを使用することができ、あなたのコードを作成することをもう少し同期見て(それがない場合でも):

    Babelを使用して
    const Promise  = require('bluebird'); 
    const MongoClient = require('mongodb').MongoClient; 
    
    let checkUpdateTime = Promise.coroutine(function* (db, last_updated){ 
        let collection = db.collection(last_updated); 
        yield collection.insert({ a : 1 }); 
        return yield collection.find({ a : 1 }).toArray(); 
    }); 
    
    Promise.coroutine(function *() { 
        let db = yield MongoClient.connect('mongodb://localhost/test'); 
        let updateTimes = yield checkUpdateTime(db, 'foobar'); 
        console.log(updateTimes); 
    })(); 
    

    またはasync/await、:

    const MongoClient = require('mongodb').MongoClient; 
    
    async function checkUpdateTime(db, last_updated) { 
        let collection = db.collection(last_updated); 
        await collection.insert({ a : 1 }); 
        return await collection.find({ a : 1 }).toArray(); 
    } 
    
    (async function() { 
        let db = await MongoClient.connect('mongodb://localhost/test'); 
        let updateTimes = await checkUpdateTime(db, 'foobar'); 
        console.log(updateTimes); 
    })(); 
    
    +0

    '"あなたは""を選択することはできません。彼はすることができます。 'async/await'を使用します。 –

    +0

    @vp_arthはまだそれを同期させません(ヒントは名前に "async" ;-)です)。それは、私がそれを例として追加した理由です。 – robertklep

    関連する問題