Question

I have tried everything I could and I googled and found some examples, I tried the examples and no joy. I'm really stuck now. So, I have mongodb on my Mac which I installed via brew. It went well. I start the server by "mongod" and it also went well. I insert some data on mongo interactive, which you can see below when I retrieved the data. I have database name "test" and collection "test"


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

Now, when I create a simple mocha test with mongoose with this code.


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;

And this is my mocha test


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");
    });
});

This is what I get from Mocha



  Vocabulary
    ✓ should get a translation of Ich (161ms)


  ✔ 1 test complete (163ms)


As you can see it doesn't ever print "mongodb is connected!" and on the find() method it also doesn't print anything.

Please help me out. Thank you so much.

Was it helpful?

Solution

I think the basic problem is that you're trying to take a synchronous approach to asynchronous activities. For example:

  1. Your mongoose connection to the database isn't actually open until you get the "open" event callback.
  2. Your get method should be returning the results in a callback that's passed into the function.
  3. Your mocha test should be using the asynchronous style where you call the done function parameter that's passed into your it callback when your test is complete.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top