I am trying to write the results of a MongoDB query to a file using the native Node.js driver. My code is the following (based on this post: Writing files in Node.js):
var query = require('./queries.js');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
    if(err) { return console.dir(err); }
    var buildsColl = db.collection('blah');
    collection.aggregate(query.test, function(err, result) {
        var JSONResult = JSON.stringify(result);
        //console.log(JSONResult);
        fs.writeFile("test.json", JSONResult, function(err) {
            if(err) {
                console.log(err);
            } else {
                console.log("The file was saved!");
            }
        });
    });
    collection.aggregate(query.next, function(err, result) {
        var JSONResult = JSON.stringify(result);
        //console.log(JSONResult);
        db.close();
    });
});
The file is written, but the contents are 'undefined.' Printing the result to the console works though.
 
     
    