我已经尝试了我能做的一切,我用谷歌搜索并找到了一些例子,我尝试了这些例子,但没有任何乐趣。我现在真的被困住了。所以,我在我的 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;
这是我的 Mocha 测试
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");
});
});
这是我从 Mocha 得到的
Vocabulary
✓ should get a translation of Ich (161ms)
✔ 1 test complete (163ms)
如您所见,它永远不会打印“mongodb已连接!”在 find() 方法上它也不会打印任何内容。
请帮帮我。非常感谢。
最佳答案
我认为基本问题是您试图对异步事件采用同步方法。例如:
- 在收到“open”事件回调之前, Mongoose 与数据库的连接实际上并未打开。
- 您的
get
方法应该在传递给函数的回调中返回结果。 - 您的 Mocha 测试应使用异步样式,您可以在测试完成时调用
done
函数参数,该参数会传递到您的it
回调中。
关于javascript - Mongoose 不会从预先存在的数据库、node.js 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776724/