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

标签 javascript node.js mongodb mongoose mocha.js

我已经尝试了我能做的一切,我用谷歌搜索并找到了一些例子,我尝试了这些例子,但没有任何乐趣。我现在真的被困住了。所以,我在我的 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() 方法上它也不会打印任何内容。

请帮帮我。非常感谢。

最佳答案

我认为基本问题是您试图对异步事件采用同步方法。例如:

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

关于javascript - Mongoose 不会从预先存在的数据库、node.js 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776724/

相关文章:

javascript - CSS::contenteditable 中元素的焦点

node.js - 使用混合数组 [{ }] 时的 Mongoose 架构验证问题

mongodb - $group by 8 条记录并进行聚合

php - Javascript 和 PHP 将数据导出到文件

javascript - 数据表不显示表格分页

javascript - npm 错误!无效版本 : "1"

java - 有没有办法在服务器端的 node.js 中运行 Java Applet?

javascript - 如何使用 nodejs-iconv 模块(或其他解决方案)在 nodejs javascript 中将字符编码从 CP932 转换为 UTF-8

javascript - 来自 mongodb 的 Angular GET 返回 [object Object]

Javascript .innerHTML 重置我的 <input type ="file">