Take a look at these two example scripts, first is Node.JS, second is Mongoose.
#!/usr/bin/env node
import { MongoClient } from 'mongodb';
import { spawn } from 'child_process';
import fs from 'fs';
const DB_URI = 'mongodb://0.0.0.0:27017';
const DB_NAME = 'DB name goes here';
const OUTPUT_DIR = 'directory output goes here';
const client = new MongoClient(DB_URI);
async function run() {
try {
await client.connect();
const db = client.db(DB_NAME);
const collections = await db.collections();
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR);
}
collections.forEach(async (c) => {
const name = c.collectionName;
await spawn('mongoexport', [
'--db',
DB_NAME,
'--collection',
name,
'--jsonArray',
'--pretty',
`--out=./${OUTPUT_DIR}/${name}.json`,
]);
});
} finally {
await client.close();
console.log(`DB Data for ${DB_NAME} has been written to ./${OUTPUT_DIR}/`);
}
}
run().catch(console.dir);
The points I want to drive home with the first, is how the connections to the DB are being established and verified before the rest of the operations. And comparatively to how similar connections work with Mongoose, as you can choose to use Mongoose for redundancy to ensure the client connection if you’d like.
Mongoose:
const mongoose = require('Mongoose');
mongoose.connect("MongoDB://localhost:<PortNumberHereDoubleCheckPort>/<DatabaseName>", {useNewUrlParser: true});
const <nameOfDbschemahere> = new mongoose.schema({
name: String,
rating: String,
quantity: Number,
someothervalue: String,
somevalue2: String,
});
const Fruit<Assuming as you call it FruitsDB> = mongoose.model("nameOfCollection" , <nameOfSchemeHere>);
const fruit = new Fruit<Because FruitsDB calling documents Fruit for this>({
name: "Watermelon",
rating: 10,
quantity: 50,
someothervalue: "Pirates love them",
somevalue2: "They are big",
});
fruit.save();