2016-08-26 2 views
6

현재 노드 4.3.2와 mongo 2.6을 사용하고 있습니다. 전체 컬렉션 (현재 컬렉션에있는 세 개의 문서)을 가져 오려고합니다. 이 코드를 사용할 때 문제가 발생합니다. 이 코드는 updateTimes을 TUN있다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); 

는 약속이 아니라 내가 기대했다 배열입니다. 목표는 배열을 편집 한 다음 나중에 컬렉션에 다시 삽입하는 것입니다. insert 문은 작동하지만 문서 검색은 단순히 예상대로 작동하지 않습니다. 나는이 코드의 많은 버전을 시도했지만 주사위는 사용하지 않았다.

나는 왜 약속이 돌아 오는지 궁금해하니? 당신이하지 않는 경우 발신자

에 약속을 반환하여 호출

  • 에 의해 전달받을 콜백을 통해

    • :

  • 답변

    9

    MongoDB의 드라이버는 비동기 작업을 처리하는 두 가지 옵션을 제공합니다 귀하의 경우와 마찬가지로 콜백을 전달하면 약속이 반환됩니다.

    여기에서 선택해야합니다. 선택할 수없는 선택은 "이 코드를 동기식으로 실행"입니다.

    나는 약속을 선호 : 당신은 항상 좀 더 화려한 가서 Promise.coroutine 같은 것을 사용할 수

    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); 
    }); 
    

    , 코드를 만들 것 보면 조금 (그렇지 않은 경우에도) 더 동기 :

    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"입니다. ;-). 그것은 그것을 좋아할지도 모르지만, 그래서 나는 이것을 예제로 추가했습니다 : D – robertklep

    관련 문제