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.

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion, but I'm still getting an 'undefined' in the file.
I just noticed that you are not checking for errors on the aggregate callback -- just updated the answer to reflect that
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.
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();
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.