Question

I'm using Visual studio with typescript. Everything in this code compiles. According to the mongoDB docs I'm using toArray correctly. I'm a little new to typescript, so I don't know if this is a typescript error or mongodb. The tests variable seems to have a method toArray but when I call it nothing returns. The console.log call isn't even ran. According to the docs and the typescript samples this is the correct way to do it. Can anyone share with me any errors in my code, or the "correct" way to do this?

///<reference path="c:\DefinitelyTyped\mongodb\mongodb.d.ts"/>

import mongodb = require("mongodb")

var server = new mongodb.Server('localhost',27017, { auto_reconnect: true})
var db = new mongodb.Db('test', server, { w: 1 });

export interface Test {
    _id: mongodb.ObjectID;
    a: number;
}

db.open(function () { });

export function getTest(callback: (test: any) => void): void {

    db.collection('test', function (err, test_collection) {
        // test_collection.find().toArray -- this doesn't work either
        test_collection.find(function (err, tests) {
            console.log(tests, 'from getTest') // log's an object with `toArray` method
            tests.toArray(function (err, docs) { // nothing returned.  Seems like the callback isn't ran
                if (err) { console.log(err) }
                console.log(docs, 'from toArray')
                callback(docs)
            })
        })
    })
}
Was it helpful?

Solution

You problem seems to be not placing your function within the db.open method's callback in general:

var mongodb = require("mongodb");

var server = new mongodb.Server('localhost', 27017, { auto_reconnect: true });
var db = new mongodb.Db('test', server, { w: 1 });

db.open(function() {

  db.createCollection('test', function(err, collection) {

    collection.find().toArray(function(err,docs) {

      console.log( docs );

    });

  });

});

You generally need to make sure a connection is open before doing anything

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top