NodeJS Ekspor Semua Koleksi MongoDB
const MongoClient = require('mongodb').MongoClient;
const fs = require('fs');
const dbName = 'database1';
const client = new MongoClient('db_url', {useUnifiedTopology:true,useNewUrlParser: true, });
client.connect(function(err) {
console.log('Connected successfully to server');
const db = client.db(dbName);
var collections = [ 'collection1', 'collection2' ];
collections.forEach(async collection => {
var documents = await getDocuments(db, collection);
try {
// Write files outside of server directory
// prevents app restarts on nodemon
fs.writeFile("../"+collection+'.json', JSON.stringify(docus), err => {
});
console.log('Done writing to file.');
} catch (err) {
console.log('Error writing to file', err)
}
})
});
async function getDocuments(db, collection) {
return await db.collection(collection).find({}).toArray()
};
Scary Shark