0

I am trying to connect to our internal mongodb cloud DB. I am getting an error cursor.map is not a function. How to solve this problem and I'm not able to find what is causing this error.

const dbConnectionUrl = `mongodb://${user}:${encodeURIComponent(pwd)}@0000000000.dev.cloud.company.net:27017/admin?retryWrites=true&w=majority`;



   const arr = [];
    MongoClient.connect(dbConnectionUrl, {
            useNewUrlParser: true, 
            useUnifiedTopology: true,
        },function(err, client){
            assert.equal(null, err);
            const cursor = client.db('tss-db').collection('jenkins-inventory').find({"instance" : "build01"}).toArray();
            cursor.map(function(instances, err){
                assert.equal(null, err);
                    arr.push(instances);
                    console.log(instances)
                }, 
                function(){
                    client.close()
            res.render('L2');        
        });
    });```
NB_775
  • 3
  • 3

1 Answers1

0

toArray does not return an array. toArray involves pulling all the objects out of the Cursor, which can take a long time and is therefore done asynchronously .

toArray takes a callback and returns a then-able Promise, either of which can be used to execute a function after the Cursor has had all its objects put into an array:

someCursor.toArray(function(resultingArray) {
    // do something with resultingArray
});

or

someCursor.toArray().then(function(resultingArray) {
    // do something with resultingArray
});

Note that either option will run chronologically after the Cursor is emptied out, which could take a long time. In the mean time, other code may run; see Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Also you code is a little hard to read, and does something that doesn't make sense to me:

  • The indentation around the map is confusing
  • You pass a second function argument into map (you do cursor.map(function() { ... }, function() { ... }) which doesn't do anything meaningful
  • if the only meaningful thing you do in .map is add elements to another array, you can use the result of the map directly instead: arr = cursor.map(...) (or if you want to be selective, use filter).
apsillers
  • 112,806
  • 17
  • 235
  • 239