【问题标题】:Mongoose won't retrieve data from preexisting database, node.jsMongoose 不会从预先存在的数据库 node.js 中检索数据
【发布时间】:2012-06-02 08:28:20
【问题描述】:

我已经尽我所能尝试了,我在谷歌上搜索并找到了一些示例,我尝试了这些示例,但没有任何乐趣。我现在真的被困住了。所以,我的 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 is connected!”在 find() 方法上它也不会打印任何东西。

请帮帮我。非常感谢。

【问题讨论】:

    标签: javascript node.js mongodb mongoose mocha.js


    【解决方案1】:

    我认为基本问题是您试图对异步活动采取同步方法。例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2018-11-25
      • 2020-09-25
      相关资源
      最近更新 更多