4

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.

Community
  • 1
  • 1
JamesE
  • 3,833
  • 9
  • 44
  • 82

2 Answers2

2

Your code is not checking the err on the aggregate callback.

You are likely getting an Mongo error and the result is undefined in that case...

Other thing I could suspect is that you are getting multiple callbacks -- each one of them creates a new files, erasing the content.

Try using fs.appendFile instead of fs.writeFile and see if you are getting the expected data (plus the unwanted undefined)

Soren
  • 14,402
  • 4
  • 41
  • 67
  • Thanks for the suggestion, but I'm still getting an 'undefined' in the file. – JamesE May 29 '14 at 18:38
  • 1
    I just noticed that you are not checking for errors on the aggregate callback -- just updated the answer to reflect that – Soren May 29 '14 at 18:42
  • That was it. I was prematurely closing the connection to the database in a second `collection.aggregate` block. Now I just need to figure out where to put the close statement. Posted updated code above. – JamesE May 29 '14 at 19:08
2

For anyone stumbling across this the solution on where to put the db.close() is below:

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();
    });
});
JamesE
  • 3,833
  • 9
  • 44
  • 82