我正在学习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;
出了什么问题? 非常感谢你的帮助。
答案 0 :(得分:1)
您正在callback
回调函数
toArray
函数
试试这个
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);
});
};