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

Mongoose won't retrieve data from preexisting database, node.js

本文关键字:node 数据库 js 数据 检索 存在      更新时间:2023-09-26

我已经尝试了我能做的一切,我用谷歌搜索并找到了一些例子,我尝试了这些例子,但没有快乐。我现在真的被困住了。所以,我的Mac上有mongodb,我是通过brew安装的。一切进展顺利。我通过"mongod"启动服务器,它也进展顺利。我在 mongo 交互式上插入了一些数据,当我检索数据时,您可以在下面看到这些数据。我有数据库名称"测试"和集合"测试"


> 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 is connected!",并且在find()方法上它也不会打印任何内容。

请帮帮我。非常感谢。

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

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