我已尽力而为,我用Google搜索并找到了一些例子,我尝试了这些例子而没有快乐。我现在真的被困住了。所以,我在我的Mac上有mongodb,我是通过brew安装的。进展顺利。我通过“mongod”启动服务器,它也很顺利。我在mongo interactive上插入了一些数据,我在检索数据时可以看到这些数据。我有数据库名称“test”和集合“test”
> db.test.find()
{ "_id" : ObjectId("4fc27535a36ea778dd6cbdf4"), "a" : "1" }
{ "_id" : ObjectId("4fc27557a36ea778dd6cbdf5"), "Ich" : "I" }
现在,当我使用mongoose用这段代码创建一个简单的mocha测试时。
var Vocabulary = function() {
function get(german_vocab) {
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/test');
mongoose.connection.on("open", function(){
console.log("mongodb is connected!!");
});
mongoose.connection.db.collection("test", function (err, collection) {
collection.find().toArray(function(err, results) {
console.log(results);
});
});
}
return {
get : get
};
}
module.exports = Vocabulary;
这是我的摩卡测试
var should = require('should');
var Vocabulary = require('../modules/vocabulary');
describe("Vocabulary", function() {
it("should get a translation of Ich", function() {
var vocabulary = Vocabulary();
vocabulary.get("Ich");
});
});
这是我从摩卡那里得到的
Vocabulary
✓ should get a translation of Ich (161ms)
✔ 1 test complete (163ms)
正如你所看到的,它永远不会打印“mongodb已连接!”并且在find()方法上它也不会打印任何东西。
请帮帮我。非常感谢你。
答案 0 :(得分:4)
我认为基本问题是您正在尝试采用同步方法来进行异步活动。例如:
get
方法应该将结果返回到传递给函数的回调中。done
函数参数,该参数在测试完成后传递到it
回调中。