2016-04-24 66 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