Mongoose不会从预先存在的数据库node.js中检索数据

时间:2012-05-27 19:43:02

标签: javascript node.js mongodb mongoose mocha

我已尽力而为,我用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()方法上它也不会打印任何东西。

请帮帮我。非常感谢你。

1 个答案:

答案 0 :(得分:4)

我认为基本问题是您正在尝试采用同步方法来进行异步活动。例如:

  1. 在获得“开放”事件回调之前,您与数据库的mongoose连接实际上并未打开。
  2. 您的get方法应该将结果返回到传递给函数的回调中。
  3. 您的mocha测试应该使用异步样式,您可以调用done函数参数,该参数在测试完成后传递到it回调中。