Last active
August 12, 2022 03:41
-
-
Save Rendydendimara/e1e55458f9339a9880ab8da4e398c95e to your computer and use it in GitHub Desktop.
Find All Document - Database MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Script untuk membaca seluruh document pada database MongoDB, kemudian di simpan kedalam sebuah file hasilnya. | |
| */ | |
| const mongoose = require('mongoose') | |
| const fs = require('fs'); | |
| const databaseUrl = 'mongodb://127.0.0.1:27017/databaseName' | |
| let seconds = 10; | |
| mongoose.connect(databaseUrl) | |
| /** | |
| * | |
| * @param {string} name | |
| * @param {function} cb | |
| * Fungsi untuk membaca document dalam collection | |
| */ | |
| function find(name, cb) { | |
| mongoose.connection.db.collection(name, async function (err, collection) { | |
| collection.find().toArray(cb); | |
| }); | |
| } | |
| mongoose.connection.on('connected', () => { | |
| const fileaname = `alldocs-${new Date().getTime()}.js` // filename-timestamps.format | |
| // Baca semua collection yang ada | |
| mongoose.connection.db.listCollections().toArray(async function (err, names) { | |
| const data = [] | |
| for (const col of names) { | |
| // Looping mencari document berdasarkan nama collection | |
| find(col.name, function (err, docs) { | |
| data.push({ | |
| collectionName: col.name, | |
| docs: docs | |
| }); | |
| }); | |
| } | |
| // Jeda waktu sebelum disimpan kedalam file | |
| console.log("Tunggu sampai 1") | |
| setTimeout(() => { | |
| // Ubah ke format string json hasil pencarian documents | |
| fs.writeFile(fileaname, JSON.stringify(data), err => { | |
| if (err) { | |
| console.error(err); | |
| } | |
| console.log('\nsukses') | |
| process.exit() | |
| }); | |
| }, 10020) // jeda 10 detik dimulai dari script dieksekusi | |
| setInterval(() => { | |
| process.stdout.write(`${seconds} `); | |
| seconds--; | |
| }, 1000) | |
| }) | |
| }) | |
| /** | |
| * Reference: | |
| * - https://www.mongodb.com/docs/manual/reference/command/listCollections/ | |
| * - https://mongoosejs.com/docs/guide.html | |
| * | |
| * Tools untuk parser json format: https://jsonformatter.org/json-parser | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment