2012-05-27 38 views
0

我尝试了所有我可以使用的方法,并且搜索了一些例子,我尝试了这些例子并且没有快乐。我现在真的被卡住了。所以,我通过brew安装了我的Mac上的mongodb。进展顺利。我用“mongod”启动服务器,它也运行良好。我在mongo interactive上插入一些数据,当我检索数据时,可以在下面看到这些数据。我有数据库名称“测试”并集“测试”Mongoose不会从先前存在的数据库中检索数据,node.js

 

> db.test.find() 
{ "_id" : ObjectId("4fc27535a36ea778dd6cbdf4"), "a" : "1" } 
{ "_id" : ObjectId("4fc27557a36ea778dd6cbdf5"), "Ich" : "I" } 
 

现在,当我创建这个代码猫鼬一个简单的摩卡测试。

 

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()方法上它也不会打印任何东西。

请帮我一把。非常感谢。

回答

4

我认为最基本的问题是,你正试图采取同步方法来异步活动。例如:

  1. 您的与数据库的猫鼬连接实际上并没有打开,直到您收到“open”事件回调。
  2. 你的get方法应该返回一个回调函数中的结果。
  3. 您的摩卡测试应该使用异步样式,您可以在测试完成时调用传入it回调函数的done函数参数。
+0

非常感谢。有用!!! – toy