2016-04-24 65 views
1

我正在學習MongoDb,模塊的練習是關於MongoDb中的一個函數,用於返回數據庫中的匹配項,並通過參數「Director」,但我沒有通過測試。這是我的代碼:函數錯誤未通過測試

在movies.js

 exports.byDirector = function(db, director, callback) { 
    // TODO: implement 

    db.collection('movies').find(
    {"director" : director}).sort({title : 1}).toArray(function(error, docs){ 
    if (error){ 
     console.log(error); 
     process.exit(1); 
    } 
    docs.forEach(function(doc){ 
     console.log(JSON.stringify(doc)); 
    }); 
    process.exit(0); 
    }) 
    callback(null, []); 
}; 

這是函數的測試:

it('returns multiple results ordered by title', function(done) { 
    dbInterface.byDirector(db, 'George Lucas', function(error, docs) { 
     assert.ifError(error); 
     assert.ok(Array.isArray(docs)); 
     assert.equal(docs.length, 4); 
     assert.equal(docs[0].title, 'Attack of the Clones'); 
     assert.equal(docs[1].title, 'Revenge of the Sith'); 
     assert.equal(docs[2].title, 'Star Wars'); 
     assert.equal(docs[3].title, 'The Phantom Menace'); 
     docs.forEach(function(doc) { 
     delete doc._id; 
     }); 
     assert.deepEqual(Object.keys(docs[0]), ['title', 'year', 'director']); 
     ++succeeded; 
     georgeLucasMovies = docs; 
     done(); 
    }); 
    }); 
    var succeeded = 3; 

有什麼不對? 非常感謝您的幫助。

回答

1

您呼叫的toArray回調函數

callback功能試試這個

exports.byDirector = function(db, director, callback) { 
    // TODO: implement 

    db.collection('movies').find(
    {"director" : director}).sort({title : 1}).toArray(function(error, docs){ 
    if (error){ 
     callback(err, null); 
    } 
    docs.forEach(function(doc){ 
     console.log(JSON.stringify(doc)); 
    }); 
    callback(null, docs); 
    }); 
}; 
+1

太謝謝你了。它完美地工作 – TibyDublin