I get and store the data from mongoDB into txt file by using the following code. But when I open txt file. Nothing is saved.
var express = require('express');
var router = express.Router();
var fs = require('fs');
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;
fs.writeFile("/tmp/test", data, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
//console.log(data);
});
}
});
It's result of console.log(data);
[ { email: '[email protected]' } ]
[ { email: '[email protected]' } ]
[]
[ { email: '[email protected]' } ]
.......
How can store result of MongoDB query in text file ?
mongodb.connect('mongodb://127.0.0.1:27017/data', function (err, db) {
if (err) throw err;
var test = db.collection('test');
recursiveadd(0,10,"",function(err,data){
if (err) {
return console.log(err);
}else{
fs.writeFile("/tmp/test", data, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
})
});
function recursiveadd(i,n,datatofile,cb){
if(i>n){
cb(undefined,"success");
return;
}
test.find({
"number": i
}, {
"email": 1,
"_id": 0
}).toArray(function (err, data) {
if (err)cb(err);
datatofile = datatofile + " " + JSON.stringify(data);
});
recursiveadd(i++,n,datatofile,cb);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments