Writing MongoDB result to a file using the built-in Node.js driver

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 to 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". However, printing the result on the console works.

+4
source share
2 answers

Your code does not validate erron a summary callback.

You will probably get a Mongo error, and the result will be undefinedin this case ...

I suspect that you are getting several callbacks - each of them creates new files, erasing the contents.

fs.appendFile fs.writeFile , ( undefined)

+2

, , , db.close(), :

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();
    });
});
+2

Source: https://habr.com/ru/post/1542533/


All Articles