1

I am currently able to run .find().forEach(function(result)) and use console.log to see what was returned from my MongoDB server using Node.js. Yet when I attempt to do array.push(result.name) the array is not updated. Below is the script that I am using:

// Create temp array to store orders
var orderArray = [];
// Connect to Orders
MongoClient.connect('mongodb://10.254.17.115:27017/Orders', function(err, db) {
    // Handle errors
    assert.equal(null, err);

    var found = db.collection('Orders').find().forEach(function (result) {
        orderArray.push(result.OrderID);
        console.log(result.OrderID);
    });

    //socket.emit('GetOrders', orderArray);
});
// Return order array
console.log("Array used for debug " + orderArray);

I would assume that the script I used would work since the scope of orderArray[] is able to reach inside and outside the .find() function. Would anybody know a fix for this?

  • you have that equal sign after orderArray, assuming thats not really in the code? – omarjmh Jul 07 '16 at 13:37
  • 3
    `orderArray` is `[]` when you accessed it. `.find()` is **asynchronous** operation. See [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tushar Jul 07 '16 at 13:37
  • @JordanHendrix It's not really in the code, just a typo. – Josh Myerson Jul 07 '16 at 13:43
  • tushar comment is the right one – omarjmh Jul 07 '16 at 13:44

0 Answers0