0

I have small code to get data from mongoDB.

var express = require('express'); 
var router = express.Router(); 
var mongodb = require('mongodb').MongoClient;
mongodb.connect('mongodb://127.0.0.1:27017/data', function(err, db) {
  if (err) throw err;
  var test = db.collection('test');
  for (var i = 0; i < 10; i++)
  {
    test.find({ "number": i }, {"email": 1, "_id": 0}).toArray(function (err,data) {
      if (err) throw err;
      console.log(data);
  });
  }
});

When console.log(data). I got a result like this

[ { email: 'example@email.com' } ]
[ { email: 'test@email.com' } ]
[]
[ { email: 'email@email.com' } ]
.......

How can store all results of MongoDB query above in text file or variable?

Alex Nguyen
  • 53
  • 10
  • Possible duplicate of [Writing files in Node.js](https://stackoverflow.com/questions/2496710/writing-files-in-node-js) – Hassan Imam Feb 13 '18 at 17:32
  • You already have the result of your query in the `data` variable :o – Yomansk8 Feb 13 '18 at 17:32
  • @Yomansk8 yep. But how can I store value in `data` to a variable or file? `I tried fs.writeFile("/tmp/test", data, function(err)` but it not ok – Alex Nguyen Feb 14 '18 at 06:40

0 Answers0